<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><link rel="stylesheet" type="text/css" href="manual.css"/><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Introduction to Nintendo DS Programming</title><meta name="generator" content="DocBook XSL Stylesheets V1.71.0" /></head><body><div class="book" lang="en" xml:lang="en"><div class="titlepage"><div><div><h1 class="title"><a id="id2479397"></a>Introduction to Nintendo DS Programming</h1></div><div><div class="author"><h3 class="author"><span class="firstname">Jaeden</span> <span class="surname">Amero</span></h3></div></div><div><p class="copyright">Copyright © 2006-2008 Jaeden
        Amero</p></div><div><div class="revhistory"><table border="1" width="100%" summary="Revision history"><tr><th align="left" valign="top" colspan="3"><b>Revision History</b></th></tr><tr><td align="left">Revision 6.0</td><td align="left">03 Jan 2008</td><td align="left">jna</td></tr><tr><td align="left" colspan="3">This manual now covers additional aspects of
                Nintendo DS Programming including multiple sprites, multiple
                backgrounds, multiple palettes, the touch screen, Slot-1
                devices, and more. The manual's case study has undergone a
                significant rewrite and covers more ground than ever
                before.</td></tr><tr><td align="left">Revision 5.0</td><td align="left">31 Mar 2007</td><td align="left">jna</td></tr><tr><td align="left" colspan="3">Made Editing improvements. Manual is now DocBook
                formatted.</td></tr><tr><td align="left">Revision 4.0</td><td align="left">31 Oct 2006</td><td align="left">jna</td></tr><tr><td align="left" colspan="3">Added VRAM Appendix, updated page layout, fixed even
                more typos.</td></tr><tr><td align="left">Revision 3.0</td><td align="left">23 Sep 2006</td><td align="left">jna</td></tr><tr><td align="left" colspan="3">Added a sound chapter</td></tr><tr><td align="left">Revision 2.2</td><td align="left">12 July 2006</td><td align="left">jna</td></tr><tr><td align="left" colspan="3">Various typo fixes</td></tr><tr><td align="left">Revision 2.1</td><td align="left">13 May 2006</td><td align="left">jna</td></tr><tr><td align="left" colspan="3">Fixed some code, spelling, and stupid little extra
                words.</td></tr><tr><td align="left">Revision 2.1</td><td align="left">21 Mar 2006</td><td align="left">jna</td></tr><tr><td align="left" colspan="3">Finalized many chapters and improved
                code.</td></tr></table></div></div></div><hr /></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="preface"><a href="#id2479075">Preface</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2479081">The Main Issue</a></span></dt><dt><span class="sect1"><a href="#id2479122">The Solution</a></span></dt><dt><span class="sect1"><a href="#id2479145">How to Use this Manual</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2479185">1. Politics of the Nintendo DS Homebrew Movement</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2479191">Background Information</a></span></dt><dt><span class="sect1"><a href="#id2479241">Is Homebrew Legal?</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2479708">2. What is a passthrough device and how do I use one?</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2479713">Purpose of the Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2479734">How a PassMe Works</a></span></dt><dt><span class="sect1"><a href="#id2479758">History of the Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2479829">The Future is Now, and Now, and Now, and Now</a></span></dt><dt><span class="sect1"><a href="#id2479851">About the NoPass</a></span></dt><dt><span class="sect1"><a href="#id2479871">About Slot-1 Devices</a></span></dt><dt><span class="sect1"><a href="#id2479893">How do I get a Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2480142">Which Passthrough Should I Buy?</a></span></dt><dt><span class="sect1"><a href="#id2480173">How would I choose an old style passthrough?</a></span></dt><dt><span class="sect1"><a href="#id2532200">PassMe 2 Buying Tips</a></span></dt><dt><span class="sect1"><a href="#id2532222">How do I use my Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2532269">What to do with your Passthrough</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2532307">3. How do I get programs into my Nintendo DS?</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2532313">The Methods</a></span></dt><dt><span class="sect1"><a href="#id2532370">Which Slot-1 Device should I buy?</a></span></dt><dt><span class="sect1"><a href="#id2532387">What is DLDI?</a></span></dt><dt><span class="sect1"><a href="#id2532425">So, which Slot-1 devices are good?</a></span></dt><dt><span class="sect1"><a href="#id2532442">R4DS</a></span></dt><dt><span class="sect1"><a href="#id2532486">M3 Real</a></span></dt><dt><span class="sect1"><a href="#id2532531">Cyclo DS Evolution</a></span></dt><dt><span class="sect1"><a href="#id2532602">Where do I get one of these Slot-1 devices?</a></span></dt><dt><span class="sect1"><a href="#id2532625">The Slot-2 Device of Choice</a></span></dt><dt><span class="sect1"><a href="#id2532706">Running Multiple Software Titles</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2532768">4. How do I create programs?</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2532773">All About devkitPro</a></span></dt><dt><span class="sect1"><a href="#id2532804">The Wonderful World of libnds</a></span></dt><dt><span class="sect1"><a href="#id2532838">Installing devkitARM</a></span></dt><dt><span class="sect1"><a href="#id2532860">Installing libnds from source</a></span></dt><dt><span class="sect1"><a href="#id2533032">The Next Step</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2533061">5. How do I display a background?</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2533067">Some Background Information</a></span></dt><dt><span class="sect1"><a href="#id2533166">The 2D Graphics Engines</a></span></dt><dt><span class="sect1"><a href="#id2533198">The Fifth Mode</a></span></dt><dt><span class="sect1"><a href="#id2533301">A Fine Affine Background</a></span></dt><dt><span class="sect1"><a href="#id2533340">Coding with this Manual</a></span></dt><dt><span class="sect1"><a href="#id2533428">Initializing the Hardware</a></span></dt><dt><span class="sect1"><a href="#id2533482">Configuring the VRAM Banks</a></span></dt><dt><span class="sect1"><a href="#id2533730">Setting up the Affine Backgrounds</a></span></dt><dt><span class="sect1"><a href="#id2533874">Fixed Point Number Primer</a></span></dt><dt><span class="sect1"><a href="#id2533953">The Basics of DMA</a></span></dt><dt><span class="sect1"><a href="#id2534164">Working with the Makefile</a></span></dt><dt><span class="sect1"><a href="#id2534271">Gritty Crash Course</a></span></dt><dt><span class="sect1"><a href="#id2534315">Putting in the Star Fields</a></span></dt><dt><span class="sect1"><a href="#id2534363">Compiling</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2534437">6. What is a sprite? How do I use them?</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2534443">Magical Fairies?</a></span></dt><dt><span class="sect1"><a href="#id2534462">The OAM</a></span></dt><dt><span class="sect1"><a href="#id2534481">Information About the Sprite Hardware</a></span></dt><dt><span class="sect1"><a href="#id2534510">How Sprites are Stored in Memory</a></span></dt><dt><span class="sect1"><a href="#id2534620">Sprite Attributes</a></span></dt><dt><span class="sect1"><a href="#id2534689">Updating the OAM</a></span></dt><dt><span class="sect1"><a href="#id2534738">Initializing the OAM</a></span></dt><dt><span class="sect1"><a href="#id2534796">Rotating Sprites</a></span></dt><dt><span class="sect1"><a href="#id2534866">Showing and Hiding Sprites</a></span></dt><dt><span class="sect1"><a href="#id2534943">Moving Sprites</a></span></dt><dt><span class="sect1"><a href="#id2534983">Setting Sprite Priorities</a></span></dt><dt><span class="sect1"><a href="#id2535031">Using the Sprites</a></span></dt><dt><span class="sect1"><a href="#id2535058">Setting up VRAM for Sprites</a></span></dt><dt><span class="sect1"><a href="#id2535133">Sprite Tile Addressing</a></span></dt><dt><span class="sect1"><a href="#id2535219">Loading in a Sprite</a></span></dt><dt><span class="sect1"><a href="#id2535573">What are assertions?</a></span></dt><dt><span class="sect1"><a href="#id2535639">Displaying the Sprites</a></span></dt><dt><span class="sect1"><a href="#id2535692">Compiling</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2535783">7. Basic Game Mechanics Applied to the Space Shooter Genre</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2535790">The Importance of Object Oriented Programming</a></span></dt><dt><span class="sect1"><a href="#id2535810">The Ship Class</a></span></dt><dt><span class="sect1"><a href="#id2535955">Making the Ship Class</a></span></dt><dt><span class="sect1"><a href="#id2535986">The Constructor</a></span></dt><dt><span class="sect1"><a href="#id2536004">Acceleration</a></span></dt><dt><span class="sect1"><a href="#id2536067">Moving the Ship</a></span></dt><dt><span class="sect1"><a href="#id2536095">Reversing the Ship's Direction</a></span></dt><dt><span class="sect1"><a href="#id2536124">Rotating the Ship</a></span></dt><dt><span class="sect1"><a href="#id2536153">Getting the Ship's Position</a></span></dt><dt><span class="sect1"><a href="#id2536178">Getting the Ship's Angle</a></span></dt><dt><span class="sect1"><a href="#id2536267">Linking the Ship into our Program</a></span></dt><dt><span class="sect1"><a href="#id2536331">Creating the Main Game Loop</a></span></dt><dt><span class="sect1"><a href="#id2536436">Compiling</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2536488">8. Nintendo DS Input Systems</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2536494">Overview</a></span></dt><dt><span class="sect1"><a href="#id2536520">Key Input</a></span></dt><dt><span class="sect1"><a href="#id2536822">Touch!</a></span></dt><dt><span class="sect1"><a href="#id2536885">Writing an Input Updating Function</a></span></dt><dt><span class="sect1"><a href="#id2536929">Writing an Input Handling Function</a></span></dt><dt><span class="sect1"><a href="#id2537045">Creating the Main Game Loop, Again</a></span></dt><dt><span class="sect1"><a href="#id2537179">Compiling</a></span></dt></dl></dd><dt><span class="chapter"><a href="#id2537262">9. What about the sounds?</a></span></dt><dd><dl><dt><span class="sect1"><a href="#id2537267">A Sound Theory</a></span></dt><dt><span class="sect1"><a href="#id2537310">The Hardware</a></span></dt><dt><span class="sect1"><a href="#id2537335">Making the Sounds</a></span></dt><dt><span class="sect1"><a href="#id2537399">Using the Sounds</a></span></dt><dt><span class="sect1"><a href="#id2537435">Getting Down with the Code</a></span></dt><dt><span class="sect1"><a href="#id2537624">Wait, What's Going on Here?</a></span></dt><dt><span class="sect1"><a href="#id2537669">The Need for Inter-processor Communication</a></span></dt><dt><span class="sect1"><a href="#id2537694">Compiling</a></span></dt></dl></dd></dl></div><div class="list-of-figures"><p><b>List of Figures</b></p><dl><dt>2.1. <a href="#id2479797">Picture of an early PassMe (left) and an FPGA
                (right)</a></dt><dt>2.2. <a href="#passme_in_use">The PassMe inserted into the DS card slot</a></dt><dt>3.1. <a href="#gbamp_vs_gba_flash_cart">Comparison of GBAMP (left) and a GBA flash cart (right)
                inserted into a DS</a></dt><dt>5.1. <a href="#raster_display">The Raster Display</a></dt><dt>5.2. <a href="#libnds_affine_bg_api">libnds Affine Background API</a></dt><dt>5.3. <a href="#fixed_point">Integer variables can be used to represent
                fractions.</a></dt><dt>5.4. <a href="#chapter_5_screen_shot">The program should look like this when run.</a></dt><dt>6.1. <a href="#sprite_tile_layout">
                    The upper text shows information as it would be on a
                    non-tiled background. The lower text shows the same data,
                    tiled, for use in tiled graphic modes.
                </a></dt><dt>6.2. <a href="#chapter_6_screen_shot">Output with both backgrounds and a sprite.</a></dt><dt>8.1. <a href="#chapter_8_screen_shot">Flying around in the Orange Shuttle.</a></dt><dt>9.1. <a href="#chapter_9_screen_shot">Flying around in the Orange Shuttle, with sound!</a></dt></dl></div><div class="list-of-tables"><p><b>List of Tables</b></p><dl><dt>2.1. <a href="#game_eject_firmware_table">When ejecting the game, you'll discover your
                firmware version as shown.</a></dt><dt>5.1. <a href="#mode_5_information">Mode 5 Information</a></dt><dt>5.2. <a href="#vram_bank_information">VRAM Bank Information</a></dt><dt>7.1. <a href="#ship_properties_and_functions">Table of Ship properties and functionality.</a></dt><dt>8.1. <a href="#libnds_key_defines">libnds Key Defines</a></dt></dl></div><div class="preface" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2479075"></a>Preface</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2479081">The Main Issue</a></span></dt><dt><span class="sect1"><a href="#id2479122">The Solution</a></span></dt><dt><span class="sect1"><a href="#id2479145">How to Use this Manual</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479081"></a>The Main Issue</h2></div></div></div><p>
                You love playing games on your Nintendo DS. Every game you've
                played has been a wonderful experience, each one leaving a
                lovely aftertaste on your gaming tongue. You may have wondered
                to yourself what it'd be like to create games, to offer your own
                software up for licking. You've drawn diagrams of games you'd
                love to make, worlds you want to share with others. But how to
                go about it? You think and are lost: you are stuck. Where do I
                start? Whats going on inside that pretty little dual-screen
                box?
            </p><p>
                This manual is designed to help you get an idea of whats going
                on inside the Nintendo DS. With a bit of effort and time,
                you'll be on your way to creating your own games. Join us, the
                homebrew community. You'll have a great time giving others a
                great time, collaborating on projects, and feeling the rush of
                intense and under pressure coding for numerous programming
                competitions competitions.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479122"></a>The Solution</h2></div></div></div><p>
                This manual is the start of the solution. In it, I will cover
                the basics of programming the Nintendo DS starting with an
                explanation of the politics behind the homebrew movement and
                through the emergence of passthrough devices, how to choose
                between a Slot-1 device or a Slot-2 device, , how to choose a
                passthrough device, setting up the programming environment,
                displaying backgrounds, using sprites, and basic game
                programming techniques. All these things will be discussed in
                the context of the creation of a simple game I concocted one
                weekend entitled "Orange Spaceship."
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479145"></a>How to Use this Manual</h2></div></div></div><p>
                I assume you know a bit of C or C++ coding. If not, spend at
                least 20 hours making a variety of programs on your own in
                addition to completing some tutorials. It doesn't matter what
                you write, so long as you make sure you have a solid
                understanding of structs, classes, the heap, loops, bitwise and
                logical operators. I recommend the following tutorial and
                reference as a great place to get started learning, <a href="http://www.cplusplus.com/doc/tutorial/" target="_top">http://www.cplusplus.com/doc/tutorial/</a> and <a href="http://www.cppreference.com/" target="_top">http://www.cppreference.com/</a>.
            </p><p>
                Next, just read through the chapters one by one, making sure
                you understand the current chapter before moving to the next.
                Code listings will be on a gray background. Follow along with
                the code listings, writing your own code based on the listings.
            </p></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2479185"></a>Chapter 1. Politics of the Nintendo DS Homebrew Movement</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2479191">Background Information</a></span></dt><dt><span class="sect1"><a href="#id2479241">Is Homebrew Legal?</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479191"></a>Background Information</h2></div></div></div><p>
                Since the Nintendo DS debut, Nintendo enthusiasts ranging from
                pre-pubescent kids to 30-year-old college dropouts have been
                wanting to develop their own games and applications for the
                Nintendo DS. Nintendo has stated that the DS stands for
                "Developer's System". For those worthy enough to land a nice
                developing contract with Nintendo, it truly is. However, most
                people will never receive this contract, special permission
                from Nintendo to commercially produce games for the Nintendo
                DS. In order to obtain a contract with Nintendo, you must prove
                your worthiness by showcasing an amazing game or other piece of
                software to them. You must have a stable financial history and
                expected stable financial future. You must have ample funding
                to buy all the official Nintendo equipment to develop for the
                system. Most game development houses don't even get that far.
                Most games on the market today are put out by what is referred
                to as a publisher. Game development houses will produce their
                game partially, show it to a publisher, and the publisher (who
                already has this development contract with Nintendo) will fund
                the game development house and market their game. All this
                bureaucracy makes it very difficult for the common person to
                produce their own, personal-use games.
            </p><p>
                This is where the homebrew movement comes in. Dedicated
                hobbyists spend weeks reverse engineering the Nintendo DS
                hardware, just to make it possible for common people to produce
                for the system (by providing a cheap alternative to official
                Nintendo development). These dedicated hobbyists come from all
                walks of life and cultures, many from Europe and the U.S., and
                bring with them great knowledge. These people make up the
                homebrew movement.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479241"></a>Is Homebrew Legal?</h2></div></div></div><p>
                Homebrew is legal for a number of reasons. You own the hardware
                you reverse engineer, so you are free to do with it as you will
                so long as you don't break the law. Breaking the law would
                include breaking proprietary copy protection, pirating video
                games, publishing illegally obtained trade secrets, or
                otherwise trying to profit off someone else's hard work.
                Homebrew poses no threat to the official developer kit, as it
                is so primitive in comparison. Even if you made something to
                compete with officially produced software, it would be near
                impossible to publish it. Companies often benefit from homebrew
                communities. Although software pirates often steal from
                homebrew discoveries to pirate software, the homebrew community
                abhors piracy and takes a strong stance against it.
            </p><p>
                When you buy a piece of hardware, you own it. This means that
                you are free to break it open, dive into it, reverse engineer
                it, and so forth. You may void your warranty, but thats the
                price for learning the intimacies of any system. The only
                illegal things on this line would be to put into production and
                sell products made with patented features (without negotiating
                a production deal with he patent owner), bypassing or breaking
                copy-protection, or stealing software code. Reverse engineering
                to learn about how the hardware works and to make something fun
                for the community is totally fine.
            </p><p>
                The homebrew tools available for game programming are far
                behind anything the game company who produced the system could
                provide (the official development kits). Game system developers
                have an intimate knowledge of the hardware, as they developed
                it. The homebrew community has only outsider knowledge through
                experimentation with the hardware.
            </p><p>
                It would be close to impossible to publish a game made with
                homebrew tools. Nintendo would not license your game. It would
                be hard to find another publisher who would try to publish
                something made with homebrew tools against Nintendo's will. On
                other systems besides the Nintendo DS, this is also true.
            </p><p>
                Companies often don't have a problem with homebrew because it
                increases the demand for their gaming systems and helps them to
                learn more about their consumer base. One example of this is
                with the Xbox. The Xbox homebrew community made the Xbox do
                things that Microsoft never thought consumers wanted like
                playindie games, emulate classic game systems, run the Linux
                operating system, and so forth. Microsoft then included a lot
                of these features (excepting Linux, of course) in their most
                recent gaming console, the Xbox 360 via a system called XNA
                Game Sudio and Xbox LIVE Arcade (XBLA). If a company wants to
                squash homebrew developers for whatever reason, they'll be
                smashing an essential fan base that loves that company's
                hardware design and has the potential to improve it (all at no
                cost to the company). Homebrew caused such a high demand for
                the Xbox that it would not have been in Microsoft's best
                interests to ignore or punish it.
            </p><p>
                The downside of homebrew is that software pirates often steal
                from the discoveries of homebrew and use that information to
                bypass copy-protection and to pirate games. Some companies may
                take a stance against homebrew for this reason, but doing so is
                unproductive. Piracy is regrettably inevitable in any
                industry. It is extremely destructive, annihilating game
                development houses because publishers will no longer publish
                their games due to a high piracy rating on the platform the
                game developers are developing for. Homebrew developers know
                this, and as the amateur brothers of the official game
                developers, they share the pain. Homebrew will usually keep
                all information regarding copy-protection in high secrecy; even
                if they know how to copy games, they will not share the
                information. The homebrew community does not want to see the
                the system they so dearly love come to an early death.
            </p></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2479708"></a>Chapter 2. What is a passthrough device and how do I use one?</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2479713">Purpose of the Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2479734">How a PassMe Works</a></span></dt><dt><span class="sect1"><a href="#id2479758">History of the Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2479829">The Future is Now, and Now, and Now, and Now</a></span></dt><dt><span class="sect1"><a href="#id2479851">About the NoPass</a></span></dt><dt><span class="sect1"><a href="#id2479871">About Slot-1 Devices</a></span></dt><dt><span class="sect1"><a href="#id2479893">How do I get a Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2480142">Which Passthrough Should I Buy?</a></span></dt><dt><span class="sect1"><a href="#id2480173">How would I choose an old style passthrough?</a></span></dt><dt><span class="sect1"><a href="#id2532200">PassMe 2 Buying Tips</a></span></dt><dt><span class="sect1"><a href="#id2532222">How do I use my Passthrough</a></span></dt><dt><span class="sect1"><a href="#id2532269">What to do with your Passthrough</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479713"></a>Purpose of the Passthrough</h2></div></div></div><p>
                The purpose of the pass through is to allow the running of
                programs on the Nintendo DS through the Game Boy Advance (GBA)
                cartridge slot. This is done because normal Nintendo DS games,
                which run from the Nintendo DS (NDS) card slot, are encrypted.
                Since it might be illegal to break that encryption, as it is a
                form of proprietary copy protection, we have to get the
                Nintendo DS to run code from a different place than the NDS
                card slot. Also, it is much easier to bypass the encryption
                than to try and break it.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479734"></a>How a PassMe Works</h2></div></div></div><p>
                When the Nintendo DS first boots, it reads a header from the
                Nintendo DS card inserted into the NDS card slot. The Nintendo
                DS will read a small block of information from the beginning of
                the game, known as the header, which contains information about
                the game (including the title of the game, date it was released
                and by who, the icon, and some hardware information). This
                header contains a pointer to a location in memory to begin
                executing code. The passthrough's job is to read this header
                and modify it to point to a location someplace on the GBA
                cartridge inserted into the GBA cart slot. What location would
                this be? Why, our code of course.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479758"></a>History of the Passthrough</h2></div></div></div><p>
                DarkFader (Rafael Vuijk) may have been the first to create a
                passthrough device. He designed his passthrough with an FPGA
                (Field Programmable Gate Array) and later packaged it into a
                single CPLD. Many other people (including Kraln, Firefly, and
                Natrium42) have developed a passthrough independently from
                DarkFader, but he is self-credited as its initial creator.
            </p><p>
                Over the next few months following the creation of the
                passthrough, Lynx and Natrium42, both major players in the
                early homebrew community, started their own online stores
                selling pre-made passthrough devices called "PassMe"s. Many
                budding DS programmers bought their first passthrough from Lynx
                or Natrium42's stores (myself included). Lynx's store,
                DSPassme.com, is still up and running today, providing a great
                option when looking to purchase a passthrough device.
            </p><div class="figure"><a id="id2479797"></a><p class="title"><b>Figure 2.1. Picture of an early PassMe (left) and an FPGA
                (right)</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/passme.png" alt="Picture of an early PassMe (left) and an FPGA (right)" /></div><div class="mediaobject"><img src="images/ufb-x_profil.jpg" alt="Picture of an early PassMe (left) and an FPGA (right)" /></div></div></div><br class="figure-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479829"></a>The Future is Now, and Now, and Now, and Now</h2></div></div></div><p>
                The PassMe was the first device invented to allow homebrew
                software to be run on the Nintendo DS. After Nintendo decided
                to crack down a little harder, in efforts to prevent piracy,
                these devices no longer worked on new Nintendo DS systems. The
                community then developed the PassMe 2. This device was more
                fancy in how it bypassed the copy protection of the Nintendo DS
                and also required the operator to have more resources (a GBA
                flash cart with SRAM) and go through a more involved process.
                After a while, a device called the NoPass surfaced.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479851"></a>About the NoPass</h2></div></div></div><p>
                A NoPass pretends to be a real Nintendo DS game card. It
                contains code that is encrypted in the same manner as a real
                Nintendo DS game. The encryption was broken by Martin Korth,
                who discovered a way to dump the Nintendo DS BIOS. He then
                reverse engineered the encryption information from the BIOS
                code. NoPass devices are technically not considered
                passthroughs, since they don't bypass the copy protection of
                the Nintendo DS.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479871"></a>About Slot-1 Devices</h2></div></div></div><p>
                Recently, due to Martin Korth's work, homebrew engineers have
                discovered a way to create a device that runs homebrew software
                from the Nintendo DS card slot (Slot-1). These new devices
                contain small passthrough devices (of the NoPass style) inside
                them that allow them to bypass copy protection as well some
                means of providing memory to the Nintendo DS (via built-in
                flash memory or a microSD card slot). These devices are called
                "Slot-1 devices". The older style devices that plug into the
                GBA cart slot are referred to as "Slot-2 devices".
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2479893"></a>How do I get a Passthrough</h2></div></div></div><p>
                Today, many passthrough and NoPass devices are on the market.
                It is highly recommended by the homebrew community to buy one
                from a fellow developer and not a company that commercially
                produces hardware meant for pirating Nintendo DS software.
                Thus, one should not buy a SuperPass or SuperKey from
                SuperCard, a MagicKey or MK4-Mini from NeoFlash, a PassKey from
                G6Flash, a PassKey or Passcard from M3Adapter, or a Max Media
                Launcher from the horrid Datel (a very unprofessional company
                run by immature anti-Nintendo kiddies). Each of these companies
                manufactures hardware that is used to pirate Nintendo DS
                software and should be avoided at all costs. The best place to
                buy a passthrough device today is from <a href="http://www.dspassme.com/oscommerce/catalog/index.php" target="_top">DSPassme.com</a>.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2480142"></a>Which Passthrough Should I Buy?</h2></div></div></div><p>
                It is recommended that you purchase a NoPass or a Slot-1
                homebrew device, as these work on all Nintendo DS systems with
                no troubles or other complications whatsoever. The older
                passthroughs, like PassMe, don't work on all Nintendo DS systems,
                and the PassMe 2 requires extra work and resources to
                use, not to mention they both stick out of your Nintendo DS
                like a sore thumb and are hard to keep in your pocket.
            </p><p>
                Slot-1 devices also have many other advantages over Slot-2
                devices and passthroughs. You definitely want to get a Slot-1
                device. For instance, Slot-2 devices suck up a lot more power
                than Slot-1 devices do. This means that using a Slot-1 device
                will give you more battery life than using a Slot-2 device.
                Many Slot-1 devices also double as NoPass devices, so you don't
                need to buy both a passthrough and a Slot-2 device anymore.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2480173"></a>How would I choose an old style passthrough?</h2></div></div></div><p>
                If you still want to buy an old fashioned style passthrough,
                there are a number of things you'll need to consider. Depending
                on what kind of Nintendo DS you have, you can buy either of two
                different types of passthrough devices. The first one, akin to
                the original made by DarkFader, is the "PassMe". The PassMe
                will probably work on most early "phat" (non-Nintendo DS Lite)
                Nintendo DS systems.
            </p><p>
                However, if your Nintendo DS is newer (both phat and Lite
                systems can be new), you will most likely need a "PassMe 2". The
                need for a PassMe 2 came about because of a change in the
                firmware of newer Nintendo DS systems. These newer systems
                do not allow the header to be changed to point to code in the
                GBA slot. However, it is possible to point to code in the GBA
                carts SRAM still. The PassMe 2 points to some certain
                instructions that have been loaded into memory by the currently
                inserted DS game. This location is an SWI (software interrupt)
                call to the SRAM on the GBA port. The GBA carts SRAM contains
                the necessary code to jump to code lo- cated on GBA cart. The
                DS then is told to run this code and thus redirects to code in
                the GBA slot. Each PassMe 2 has to be programmed to work with
                one specific game, as the certain code to redirect to the GBA
                slot is found in different places within different DS games.
            </p><p>
                There are a few tricks you can pull to determine your firmware
                version. It involves pictochat and pulling a cartridge out of
                your Nintendo DS. The screen will change a certain color.
                Based on this color you can determine if you need a PassMe 2 or
                not. <a href="#game_eject_firmware_table" title="Table 2.1. When ejecting the game, you'll discover your&#10;                firmware version as shown.">Table 2.1, “When ejecting the game, you'll discover your
                firmware version as shown.”</a> will help you
                discover which firmware version you have.
            </p><div class="procedure"><a id="id2478769"></a><p class="title"><b>Procedure 2.1. Checking the Firmware Version</b></p><ol type="1"><li><p>
                        Insert and Nintendo DS game into the DS card slot.
                    </p></li><li><p>
                        Turn on the Nintendo DS. (If you have auto start
                        enabled, hold down Start and Select when you boot the
                        system.)
                    </p></li><li><p>
                        Start Pictochat by pressing the Pictochat logo on the
                        menu screen.
                    </p></li><li><p>
                        Join any room you wish.
                    </p></li><li><p>
                        Remove the Nintendo DS game inserted into the back of
                        the system.
                    </p></li><li><p>
                        You will notice either Pictochat freezing or both
                        screens will change color.
                    </p></li></ol></div><div class="table"><a id="game_eject_firmware_table"></a><p class="title"><b>Table 2.1. When ejecting the game, you'll discover your
                firmware version as shown.</b></p><div class="table-contents"><table summary="When ejecting the game, you'll discover your&#10;                firmware version as shown." border="1"><colgroup><col /><col /></colgroup><thead><tr><th>Observed Results</th><th>Firmware
                            Version</th></tr></thead><tbody><tr><td>Pictochat froze</td><td>Version
                            1</td></tr><tr><td>Both screens turned
                            periwinkle</td><td>Version 2</td></tr><tr><td>Both screens turned dark
                            green</td><td>Version 3, iQue, or
                            Flashme</td></tr><tr><td>Both screens turned
                            marigold</td><td>Version 4</td></tr><tr><td>Both screens turned
                            magenta</td><td>Version 5</td></tr><tr><td>Both screens turned dark
                            blue</td><td>Version 6</td></tr></tbody></table></div></div><br class="table-break" /><p>
                It is recommended that you purchase a NoPass instead of a
                PassMe or PassMe 2 passthrough device if you are unsure which
                to get, as they are guaranteed to work with all Nintendo DS
                systems, past, present, and future. If you have a friend with a
                newer DS who may need to borrow your NoPass to play your games,
                it's always helpful to have a universal method of running them.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532200"></a>PassMe 2 Buying Tips</h2></div></div></div><p>
                When ordering a PassMe 2, be sure to select one pre-programmed
                to a common game that you own, such as the Metroid Prime
                Hunters Demo or Super Mario 64 DS. Each PassMe 2 must be
                programmed to a specific game and it is best to select a game
                that is in large supply. Also, you'll need a GBA flash cart
                with some SRAM on it. Most GBA flash carts have SRAM, but be
                sure to check your cart before trying to obtain a PassMe 2.
                Some newer GBA flash carts might only support save games on
                flash, so simply knowing that your flash cart supports save
                games isn't enough.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532222"></a>How do I use my Passthrough</h2></div></div></div><p>
                Using a passthrough device is quite simple. Simply insert a
                game into the card slot on the passthrough and plug the device
                into the DS card slot on the top of your DS, like any other
                game. <a href="#passme_in_use" title="Figure 2.2. The PassMe inserted into the DS card slot">Figure 2.2, “The PassMe inserted into the DS card slot”</a> illustrates what this
                looks like.
            </p><div class="figure"><a id="passme_in_use"></a><p class="title"><b>Figure 2.2. The PassMe inserted into the DS card slot</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/passme_insert_ds.png" alt="The PassMe inserted into the DS card slot" /></div></div></div><br class="figure-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532269"></a>What to do with your Passthrough</h2></div></div></div><p>
                One of the best things to do once you get your passthrough is
                to install a patch to your Nintendo DS firmware known as
                "FlashMe." This firmware patch allows for the running of
                unsigned wifi binaries as well as the redirecting of the
                Nintendo DS to boot from the GBA slot in NDS mode. This means
                that after installing FlashMe, you no longer need your PassMe.
                FlashMe is the preferred and recommended method of running your
                own software. You no longer have to lug around a passthrough or
                play with a large block sticking out of the back of your DS.
                Also, you can send your code via wireless multiboot (WMB), if
                you so desire, and avoid having to use a flash cart. In addition
                to all those things, in case you ever come across some
                malicious code that zaps your firmware or otherwise messes up
                your DS, FlashMe keeps a recovery program in the protected
                firmware space that you can run to save your DS. Because of
                this feature alone, FlashMe is better than the standard
                firmware. FlashMe can be obtained from <a href="http://home.comcast.net/~olimar/flashme/" target="_top">http://home.comcast.net/~olimar/flashme/</a>.
            </p></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2532307"></a>Chapter 3. How do I get programs into my Nintendo DS?</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2532313">The Methods</a></span></dt><dt><span class="sect1"><a href="#id2532370">Which Slot-1 Device should I buy?</a></span></dt><dt><span class="sect1"><a href="#id2532387">What is DLDI?</a></span></dt><dt><span class="sect1"><a href="#id2532425">So, which Slot-1 devices are good?</a></span></dt><dt><span class="sect1"><a href="#id2532442">R4DS</a></span></dt><dt><span class="sect1"><a href="#id2532486">M3 Real</a></span></dt><dt><span class="sect1"><a href="#id2532531">Cyclo DS Evolution</a></span></dt><dt><span class="sect1"><a href="#id2532602">Where do I get one of these Slot-1 devices?</a></span></dt><dt><span class="sect1"><a href="#id2532625">The Slot-2 Device of Choice</a></span></dt><dt><span class="sect1"><a href="#id2532706">Running Multiple Software Titles</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532313"></a>The Methods</h2></div></div></div><p>
                There are a few ways of getting your code into the Nintendo DS.
                The first of which is the simple GBA flash cart. These flash
                carts are generally quite expensive, have a low availability,
                and don’t hold very much memory. They fit into the phat
                Nintendo DS systems perfectly and do not stick out from the
                bottom, except on the Nintendo DS Lite, as other things do. The
                second way of running code is on a removable memory device.
                These kinds of devices come in two flavors: Slot-1 and Slot-2.
                Slot-2 devices, such as the M3 Adapter, G6 Flash, NeoFlash,
                SuperCard, and the GBA Movie Player, generally support both
                Nintendo DS and GBA software. Slot-1 devices, such as the M3
                Simply, R4DS, M3 Real, DS-X, NinjaDS, and the Cyclo DS
                Evolution, generally only support Nintendo DS software. Slot-1
                devices also fit into the Nintendo DS perfectly. The first four
                of those Slot-2 devices are produced by supporters of piracy
                and should be avoided. It is recommended to use the GBA Movie
                Player (GBAMP) if you want to use a Slot-2 device. With Slot-1
                devices, we don't have too much of a choice but to choose the
                lesser of many evils.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532370"></a>Which Slot-1 Device should I buy?</h2></div></div></div><p>
                As there are no homebrew produced devices made by hombrew
                people for homebrew people (yet), we regretfully have to buy
                devices designed and sold for piracy when buying NoPass or
                Slot-1 devices. That said, the most important feature to
                consider when buying one of these devices is DLDI support.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532387"></a>What is DLDI?</h2></div></div></div><p>
                DLDI stands for dynamically linked device interface. In order
                for the homebrew filesystem, known as libfat, to work, you'll
                need a device which supports the DLDI standard. DLDI specifies
                a system by which DLDI modules can be dynamically loaded into
                homebrew software. This allows developers to release one
                version of their homebrew which the software end users simply
                patch and then run on a device of their choice. If you buy a
                device that does not support DLDI, you will be out of luck when
                wanted to run a majority of the homebrew applications and games
                out there. Not to mention that the company producing the device
                is essentially saying, "We don't need to spend time catering to
                the homebrew community since our device is designed just for
                piracy." We'd be better off not supporting that kind of company
                with our business.
            </p><p>
                You can learn more about DLDI and how to use it at the DLDI
                Wiki website, <a href="http://dldi.drunkencoders.com/index.php?title=Main_Page" target="_top">http://dldi.drunkencoders.com/index.php?title=Main_Page</a>.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532425"></a>So, which Slot-1 devices are good?</h2></div></div></div><p>
                There are so many Slot-1 devices on the market today. Choosing
                one of them has become very difficult, as the choices are so
                many. In this manual, I'll discuss the devices I'm familiar
                with, which nifty features they propport, and how they compare
                to one another.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532442"></a>R4DS</h2></div></div></div><p>
                This device is built well. It is the most sturdy of the three.
                It uses microSD cards for storage and supports DLDI. This means
                that you can run homebrew software and use the microSD card's
                filesystem. With the most recent firmware, it can even
                automatically patch generic DLDI homebrew software with the
                proper DLDI driver for the R4DS on the fly. This means that you
                don't have to use your PC to patch your homebrew software
                before placing it onto your microSD card. The R4DS cannot use
                microSDHC cards, however. Some people have complained about the
                spring loaded microSD slot, so the makers of R4DS have removed
                it from current models. The R4DS is a great device overall and
                well supported by the Nintendo DS homebrew community, but it
                does not support running GBA software unfortunately.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532486"></a>M3 Real</h2></div></div></div><p>
                This device comes in varying configurations for your various
                needs. It comes with both a Slot-1 device and a Slot-2 device.
                The Slot-2 device is what differs between the three M3 Real
                configurations. In the first and cheapest configuration, the
                Slot-2 pack is simply a rumble pack. In the second and more
                expensive version, the Slot-2 pack is a dual rumble and RAM
                pack. This configuration will also run GBA homebrew. The flash
                cart size is kept secret by M3, for some reason. Natrium42 was
                kind enough to inform me that, after doing a few tests on the
                pack, that it is at least 8MB in size, but lacks SRAM. The
                third and most expensive configuration, dubbed the "GBA
                Expansion Package", provides a Slot-2 pack with rumble, SRAM,
                and 32MB of RAM. 
            </p><p>
                The M3 Real supports DLDI as well. I'm not sure if it can
                automatially patch homebrew with its own driver on the fly,
                however. The homebrew software may need to be patched on a PC
                before being transferred to the SD card.
            </p><p>
                The M3 Real supports microSD and microSDHC cards, unlike the
                R4DS. So if you are in the mood for massive storage, the M3
                Real can be your friend.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532531"></a>Cyclo DS Evolution</h2></div></div></div><p>
                This device has very recently come to market, but is already
                making a big impression in the community. The Cyclo DS
                Evolution has the best looking and functioning menu system of
                the three devices, in my opinion. And if you don't like it, the
                menus are skinnable with a number of skins already available
                for the device. You might be thinking, "Why would I care what
                my menus look or act like?" Well, when you use the device to
                load your software over and over and over again, bad menus
                really piss you off. When you can't use the touch screen to
                scroll up and down and select items and have to use the keys,
                but holding down the keys doesn't make the menu scroll by and
                you have to press the up and down buttons a lot to get to your
                software, you get pissed off. And yes, there really are menus
                that are this bad.
            </p><p>
                Aside from the pleasant menus, the Cyclo DS Evolution supports
                DLDI. It also features on the fly DLDI patching. I dislike
                having to patch my games on my PC before loading them onto my
                microSD card, so this is a great feature.
            </p><p>
                My favorite feature of the Cyclo DS Evolution is the "remember
                what I loaded last time and load that same program again"
                feature. Simply holding down L and R at boot will boot the last
                thing that was booted. This enables me to avoid navigating the
                menu system when I'm debugging a program and running it
                repeatedly for testing.
            </p><p>
                The Cyclo DS Evolution also has a NoPass mode where it will act
                as a NoPass to boot your GBA flash carts, a GBA Movie Player,
                or any other Slot-2 device.
            </p><p>
                As you've probably noticed, as I've written the most about the
                Cyclo DS Evolution, that I like it the best of the three
                devices. It is competitively priced with the others, which is
                good. While it doesn't support running GBA software, it feature
                rich on the Nintendo DS side of things. I recommend the Cyclo
                DS Evlolution to meet all of your Slot-1 needs and desires.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532602"></a>Where do I get one of these Slot-1 devices?</h2></div></div></div><p>
                Out of the many places to buy these devices, I've been most
                happy with electrobee. electrobee is run by a trusted member of
                the homebrew community and ships worldwide from good ol' Canada
                (as opposed to who knows where). Their prices are quite often
                the best, too. When you are ready to purchase a Slot-1 device,
                I recommend that you visit <a href="http://electrobee.com/" target="_top">http://electrobee.com/</a>.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532625"></a>The Slot-2 Device of Choice</h2></div></div></div><p>
                If you decide that GBA software development is important for
                you, you might want to consider getting a NoPass and a Slot-2
                device. The NoPass will allow you to run Nintendo DS software
                from your Slot-2 device. The Slot-2 device, on its own, will be
                able to run GBA software. If you only care about Nintendo DS
                software, a Slot-1 device will meet your needs well.
            </p><p>
                The GBA Movie Player is a wonderful device which can run your
                software from a Compact Flash card. Compact Flash cards are
                very cheap and in high supply. If you have more SD cards than
                CF cards around, unfortunately, the only way to run NDS
                software from an SD card at this time is with the SD versions
                of the SuperCard or M3 Adapter. The GBAMP also sticks out from
                the bottom of the Nintendo DS a little, as shown in <a href="#gbamp_vs_gba_flash_cart" title="Figure 3.1. Comparison of GBAMP (left) and a GBA flash cart (right)&#10;                inserted into a DS">Figure 3.1, “Comparison of GBAMP (left) and a GBA flash cart (right)
                inserted into a DS”</a>
            </p><div class="figure"><a id="gbamp_vs_gba_flash_cart"></a><p class="title"><b>Figure 3.1. Comparison of GBAMP (left) and a GBA flash cart (right)
                inserted into a DS</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/comparison_insertion.png" alt="Comparison of GBAMP (left) and a GBA flash cart (right) inserted into a DS" /></div></div></div><br class="figure-break" /><p>
                With the GBA flash cart, the process of loading your programs
                into memory is a bit slow. Also, each GBA flash cart writer is
                specific to certain carts and often have closed source drivers.
                This means that most flash carts will be incompatible with Linux
                or Macintosh computers. In actuality, the only good thing about
                a GBA flash cart is that it does not stick out from the Nintendo
                DS, as can be seen in <a href="#gbamp_vs_gba_flash_cart" title="Figure 3.1. Comparison of GBAMP (left) and a GBA flash cart (right)&#10;                inserted into a DS">Figure 3.1, “Comparison of GBAMP (left) and a GBA flash cart (right)
                inserted into a DS”</a>.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532706"></a>Running Multiple Software Titles</h2></div></div></div><p>
                If you chose to go with the GBA flash cart, you can use a
                utility called Darkain’s MultiNDS Loader to load multiple
                programs onto your flash cart. This way, you don’t have to
                re-flash your cart each time you want to run a different
                application.
            </p><p>
                If you chose to go with the GBAMP, then I’d highly recommend
                DragonMinded's DSOrganize. It supports booting multiple
                programs, text editing, address books, calendars, and more. It's
                a great application for the DS. You can get it from <a href="http://www.dragonminded.com/?loc=ndsdev/DSOrganize" target="_top">http://www.dragonminded.com/?loc=ndsdev/DSOrganize</a>.
                However, you cannot use a stock GBAMP to run NDS programs. You
                have to flash it with some custom ﬁrmware. Instructions and
                firmware are available from <a href="http://chishm.drunkencoders.com/NDSMP/index.html" target="_top">http://chishm.drunkencoders.com/NDSMP/index.html</a>.
            </p><p>
                As for Slot-1 devices, these all usually come with their own
                menu systems (often incorrectly referred to as operating
                systems). You won't have to do anything special to run multiple
                software titles.
            </p></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2532768"></a>Chapter 4. How do I create programs?</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2532773">All About devkitPro</a></span></dt><dt><span class="sect1"><a href="#id2532804">The Wonderful World of libnds</a></span></dt><dt><span class="sect1"><a href="#id2532838">Installing devkitARM</a></span></dt><dt><span class="sect1"><a href="#id2532860">Installing libnds from source</a></span></dt><dt><span class="sect1"><a href="#id2533032">The Next Step</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532773"></a>All About devkitPro</h2></div></div></div><p>
                devkitPro brand name, like Microsoft or Adobe. You don't use
                devkitPro to build your Nintendo DS software anymore than you
                write your letters with Microsoft or edit photos with Adobe.
                devkitPro produces a collection of toolchains for homebrew
                developers. Toolchains are available for Game Boy Advance,
                GP32, Playstation Portable, GameCube, and the Nintendo DS. The
                toolchain we are most interested in is known as devkitARM.
            </p><p>
                devkitARM is a specific toolchain of devkitPro. It allows the
                compiling of ARM binaries from most all computers. It is based
                on gcc, the gnu compiler collection. devkitARM includes
                everything you'll need to create software for the Nintendo DS,
                GBA, and GP32; all of which are run by the ARM processor.
                However, we will be using something to make our job much easier
                in addition to just devkitARM.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532804"></a>The Wonderful World of libnds</h2></div></div></div><p>
                libnds, the library for Nintendo DS, started out its life as
                NDSLIB. NDSLIB was a simple library created by joat (Michael
                Noland) and dovoto (Jason Rogers). The name was changed to
                libnds over the course of a few months and the maintainer has
                been changed to WinterMute (Dave Murphy).
            </p><p>
                NDSLIB started out as a collection of defines for common memory
                locations in the DS. This is useful, as you can simply
                reference BG_BMP_RAM instead of 0x06000000. Eventually, the
                library began to include structs and unions and other useful
                constructs that help to simplify the programmers job and
                abstract certain portions of the hardware from the programmer.
            </p><p>
                Today, libnds is an incredibly useful library that over 96% of
                the Nintendo DS homebrew community uses.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532838"></a>Installing devkitARM</h2></div></div></div><p>
                Installing devkitARM is quite simple. Directions are already
                documented on their website. Visit <a href="http://www.devkitpro.org/setup.shtml" target="_top">http://www.devkitpro.org/setup.shtml</a> for directions.
                Although more geared towards Windows, the installation is
                fairly straight forward. Automated installers are available for
                Windows, Macintosh, and Linux.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2532860"></a>Installing libnds from source</h2></div></div></div><p>
                libnds's source install is less documented than devkitPro's
                source install, but is also quite simple in comparison. libnds
                is automatically installed by the automated installers of
                devkitARM. However, if you want to view the libnds source code,
                you'll have to install it from source.
            </p><div class="procedure"><a id="id2532875"></a><p class="title"><b>Procedure 4.1. To install libnds from source</b></p><ol type="1"><li><p>
                        Simply download the latest source from <a href="http://sourceforge.net/project/showfiles.php%3Fgroup_id%3D114505%26package_id%3D151608" target="_top">SourceForge.net</a>.
                    </p></li><li><p>
                        Extract it to <code class="filename">$DEVKITPRO/libnds</code>.
                    </p><pre class="screen">
                        <code class="prompt">patater@patater.com:~$</code><span><strong class="command">mkdir
                        $DEVKITPRO/libnds</strong></span>
                        <code class="prompt">patater@patater.com:~$</code><span><strong class="command">mv
                        libnds-src-*.tar $DEVKITPRO/libnds/</strong></span>
                        <code class="prompt">patater@patater.com:~$</code><span><strong class="command">cd
                        $DEVKITPRO/libnds</strong></span>
                        <code class="prompt">patater@patater.com:~$</code><span><strong class="command">tar
                        -xvjf libnds-src-*.tar.bz2 $DEVKITPRO/libnds</strong></span>
                    </pre></li><li><p>
                        Change your current directory to
                        <code class="filename">$DEVKITPRO/libnds</code> and type
                        <span><strong class="command">make</strong></span>.
                    </p><pre class="screen">
                        <code class="prompt">patater@patater.com:~$</code><span><strong class="command">cd
                        $DEVKITPRO/libnds</strong></span>
                        <code class="prompt">patater@patater.com:~$</code><span><strong class="command">make</strong></span>
                    </pre></li><li><p>
                        If devkitARM is installed properly, libnds will compile
                        in a matter of seconds and you'll be on your way to
                        developing software for the Nintendo DS.
                    </p></li></ol></div></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533032"></a>The Next Step</h2></div></div></div><p>
                Now that you have devkitARM and libnds installed on your
                computer, you have everything you need to start coding,
                excepting perhaps a bit of knowledge on how to code
                specifically for the unique harware of the Nintendo DS. In the
                next chapter, we'll cover the basics of displaying a bitmap on
                the screen.
            </p><div class="mediaobject"><img src="images/devkitlogo.png" /></div></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2533061"></a>Chapter 5. How do I display a background?</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2533067">Some Background Information</a></span></dt><dt><span class="sect1"><a href="#id2533166">The 2D Graphics Engines</a></span></dt><dt><span class="sect1"><a href="#id2533198">The Fifth Mode</a></span></dt><dt><span class="sect1"><a href="#id2533301">A Fine Affine Background</a></span></dt><dt><span class="sect1"><a href="#id2533340">Coding with this Manual</a></span></dt><dt><span class="sect1"><a href="#id2533428">Initializing the Hardware</a></span></dt><dt><span class="sect1"><a href="#id2533482">Configuring the VRAM Banks</a></span></dt><dt><span class="sect1"><a href="#id2533730">Setting up the Affine Backgrounds</a></span></dt><dt><span class="sect1"><a href="#id2533874">Fixed Point Number Primer</a></span></dt><dt><span class="sect1"><a href="#id2533953">The Basics of DMA</a></span></dt><dt><span class="sect1"><a href="#id2534164">Working with the Makefile</a></span></dt><dt><span class="sect1"><a href="#id2534271">Gritty Crash Course</a></span></dt><dt><span class="sect1"><a href="#id2534315">Putting in the Star Fields</a></span></dt><dt><span class="sect1"><a href="#id2534363">Compiling</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533067"></a>Some Background Information</h2></div></div></div><p>
                Since the beginning of time, humans have used raster displays
                to draw electronic images. Raster images aren't used too much
                anymore, in practice. However, most all displays still act like
                raster displays from a programming perspective. Each physical
                display on the Nintendo DS is actually an LCD screen which
                works nothing like a raster display in actuality, but the
                electronics that control it provide an interface to the
                graphics engines on the Nintendo DS that is very much like a
                raster display.
            </p><p>
                So what is a raster display? Put simply, it is just like a
                television display. A beam of electrons blasts away at the back
                of a phoshor coated screen in a deterministic way (known as a
                raster scan). The beam, from the perspective of a person
                watching the television, travels from left to right, one
                scan line at a time. The beam never blast electrons from right
                to left. After the beam reaches the right edge of the screen,
                it turns off and moves to the right and down one line. When the
                beam finally reaches the bottom line of the screen, it travels
                back up to the upper left of the screen and begins this drawing
                process all over again. <a href="#raster_display" title="Figure 5.1. The Raster Display">Figure 5.1, “The Raster Display”</a>
                illustrates this process in an exaggerated fashion.
            </p><p>
                Two things are important to remember here. First, that the
                period of time during which the beam goes from right to left
                (not drawing anything) is called the horizontal blanking
                period, or hblank. Second, that the period of time during which
                the beam goes from bottom to top (again, not drawing anything)
                is called the vertical blanking period, or vblank. Knowing
                about vblank is useful for us as Nintendo DS programmers
                because it is the period of time in which we will tell the
                Nintendo DS to draw things. If we didn't, then the Nintendo DS
                display might be in the middle of drawing the screen when we
                tell it what to draw. This would give us strange artifacts and
                is generally undesirable.
            </p><div class="figure"><a id="raster_display"></a><p class="title"><b>Figure 5.1. The Raster Display</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/raster_display.svg" alt="The Raster Display" /></div></div></div><br class="figure-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533166"></a>The 2D Graphics Engines</h2></div></div></div><p>
                The Nintendo DS has two screens. As such, it has two graphics
                engines, one for each screen. The first engine is referred to
                as the "main" engine, while the second is called the "sub"
                engine. Both of these engines can put in charge of either
                screen. By default, libnds tells the main engine to operate the
                top physical screen and the sub screen the bottom physical
                screen.
            </p><p>
                Each engine supports up to four backgrounds and up to 128
                sprites. They operate independently of each other, each with
                their own control registers, backgrounds, sprites, graphics
                data, and palettes. To use an engine, we must first turn them
                on. Then we place the engine into a certain mode of operation.
                Next, we map memory for use with the engines. Finally, we load
                their memory with graphics data and palettes and they
                automatically just draw what we've set them up to do.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533198"></a>The Fifth Mode</h2></div></div></div><p>
                Each of these graphics engines can be placed into one of seven
                different modes that support different features. In this
                manual, we'll cover one of the more common graphic modes, Mode
                5. It is commonly used because it is very flexible and allows
                for some amazing special effects. We'll learn how to display
                multiple 15-bit color 1-bit alpha <em class="glossterm">affine</em> backgrounds in this
                chapter. Mode 5 consists of four different backgrounds each
                with their own capabilities. <a href="#mode_5_information" title="Table 5.1. Mode 5 Information">Table 5.1, “Mode 5 Information”</a> shows how flexible Mode 5 can
                be.
            </p><div class="table"><a id="mode_5_information"></a><p class="title"><b>Table 5.1. Mode 5 Information</b></p><div class="table-contents"><table summary="Mode 5 Information" border="1"><colgroup><col /><col /></colgroup><thead><tr><th>Background</th><th>Purpose</th></tr></thead><tbody><tr><td>0</td><td>Tiled Mode, 2D with 3D
                            support</td></tr><tr><td>1</td><td>Tiled Mode, 2D</td></tr><tr><td>2</td><td>Extended Rotation
                            Background</td></tr><tr><td>3</td><td>Extended Rotation
                            Background</td></tr></tbody></table></div></div><br class="table-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533301"></a>A Fine Affine Background</h2></div></div></div><p>
                An affine background, also known as an external rotation
                background or exrot background, is one that has the ability to
                be transformed by an <span class="ERROR">&lt;glossaryterm&gt;affine transformation
                matrix&lt;/glossaryterm&gt;</span>. Since linear algebra is beyond the
                scope of this manual, I will cover briefly how to set up a
                basic affine background, but not get into rotating, scaling, or
                sheering it. For this manual, we'll just apply an identity
                transform, a transform that doesn't actually change the
                background, to our backgrounds. With an affine transformation
                matrix, you can rotate, scale, and sheer an affine background,
                among other interesting effects. If you want to learn about the
                cool effects you can do with an affine background and an affine
                transformation matrix, I recommend you look at Cearn's tutorial
                on affine transformations at <a href="http://www.coronac.com/tonc/text/affine.htm" target="_top">http://www.coronac.com/tonc/text/affine.htm</a>.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533340"></a>Coding with this Manual</h2></div></div></div><p>
                Since this is the first time in this manual where we'll start
                to write code, we should be aware of the resources available to
                assist us in following along with this manual. If you haven't
                already done so, download the sources that accompany this
                manual from the manual homepage at <a href="http://patater.com/manual" target="_top">http://patater.com/manual</a>. After extracting the
                sources, you'll find a folder called <code class="filename">code</code>.
                The manual provides a template for you to use with this manual
                and any other Nintendo DS programming projects you might wish
                to start developing. This template is located in the
                <code class="filename">code</code> folder and is itself a folder called
                <code class="filename">chapter_0-starting_system</code>. The
                <code class="filename">code</code> folder also contains project folders
                for each chapter. If at anytime you get stuck or if you want to
                skip a chapter, feel free to refer the completed project for
                the chapter you are stuck on or to grab the completed project
                for the chapter prior to the one you wish to skip to. To follow
                along with this manual, copy the
                <code class="filename">chapter_0-starting_system</code> folder to a nice
                place you wish to work from (I'd copy the folder to my
                <code class="filename">~/projects</code> directory and name the copy
                <code class="filename">manual</code>) and open
                <code class="filename">source/main.cpp</code> with your favorite text
                editor. (My favorite text editor is gvim.) Let's get going!
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533428"></a>Initializing the Hardware</h2></div></div></div><p>
                In order to get the hardware to do what we want, we have to
                first initialize it. This means turning on the 2D core and
                setting up a VBlank <em class="glossterm">IRQ
                handler</em>. This is where we first fall in love with
                libnds. (We'll fall in love with it repeatedly over the course
                of this manual.) libnds makes it incredibly simple to do these
                two things. Add the following code to your new
                <code class="filename">main.cpp</code> C++ code file.
            </p><pre class="programlisting">
#include &lt;nds.h&gt;

int main() {
    /*  Turn on the 2D graphics core. */
    powerON(POWER_ALL_2D);

    /*
     *  Set up interrupts.
     *
     *  We don't really get into what these do exactly at this point in the
     *  manual, but we still need to do them for now.
     */
    irqInit();
    irqSet(IRQ_VBLANK, 0);

    return 0;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533482"></a>Configuring the VRAM Banks</h2></div></div></div><p>
                After we get the basic setup done, we now have to tell the
                graphics engine where to get its display data from. The two
                graphics engines share the same VRAM; i.e. There are not two
                VRAM A banks, one for the main screen and one for the sub
                screen. We'll use these memory locations when we load the
                graphics later. Let's make a function called <code class="code"><code class="function">initVideo</code></code>.
                </p><pre class="programlisting">
void initVideo() {
    /*
     *  Map VRAM to display a background on the main and sub screens.
     * 
     *  The vramSetMainBanks function takes four arguments, one for each of the
     *  major VRAM banks. We can use it as shorthand for assigning values to
     *  each of the VRAM bank's control registers.
     *
     *  We map banks A and B to main screen background memory. This gives us
     *  256KB, which is a healthy amount for 16-bit graphics.
     *
     *  We map bank C to sub screen background memory.
     *
     *  We map bank D to LCD. This setting is generally used for when we aren't
     *  using a particular bank.
     */
    vramSetMainBanks(VRAM_A_MAIN_BG_0x06000000,
                     VRAM_B_MAIN_BG_0x06020000,
                     VRAM_C_SUB_BG_0x06200000,
                     VRAM_D_LCD);

    /*  Set the video mode on the main screen. */
    videoSetMode(MODE_5_2D | // Set the graphics mode to Mode 5
                 DISPLAY_BG2_ACTIVE | // Enable BG2 for display
                 DISPLAY_BG3_ACTIVE); //Enable BG3 for display

    /*  Set the video mode on the sub screen. */
    videoSetModeSub(MODE_5_2D | // Set the graphics mode to Mode 5
                    DISPLAY_BG3_ACTIVE); // Enable BG3 for display
}
            </pre><p>
                There are nine VRAM banks in total on the Nintendo DS. See
                <a href="#vram_bank_information" title="Table 5.2. VRAM Bank Information">Table 5.2, “VRAM Bank Information”</a> for details about them.
                Our 16bit background images take up 128KB of memory each. Thus,
                each background has to have one whole VRAM bank assigned to it.
                Not all VRAM banks can be used for all purposes, however. Refer
                to Appendix A, for more detailed information.
            </p><div class="table"><a id="vram_bank_information"></a><p class="title"><b>Table 5.2. VRAM Bank Information</b></p><div class="table-contents"><table summary="VRAM Bank Information" border="1"><colgroup><col /><col /><col /><col /></colgroup><thead><tr><th>VRAM Bank</th><th>Control Register
                            Address</th><th>Control Register</th><th>VRAM Bank
                            Size</th></tr></thead><tbody><tr><td>VRAM_A</td><td>0x04000240</td><td>VRAM_A_CR</td><td>128KB</td></tr><tr><td>VRAM_B</td><td>0x04000241</td><td>VRAM_B_CR</td><td>128KB</td></tr><tr><td>VRAM_C</td><td>0x04000242</td><td>VRAM_C_CR</td><td>128KB</td></tr><tr><td>VRAM_D</td><td>0x04000243</td><td>VRAM_D_CR</td><td>128KB</td></tr><tr><td>VRAM_E</td><td>0x04000244</td><td>VRAM_E_CR</td><td>64KB</td></tr><tr><td>VRAM_F</td><td>0x04000245</td><td>VRAM_F_CR</td><td>16KB</td></tr><tr><td>VRAM_G</td><td>0x04000246</td><td>VRAM_G_CR</td><td>16KB</td></tr><tr><td>VRAM_H</td><td>0x04000248</td><td>VRAM_H_CR</td><td>32KB</td></tr><tr><td>VRAM_I</td><td>0x04000249</td><td>VRAM_I_CR</td><td>16KB</td></tr></tbody></table></div></div><br class="table-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533730"></a>Setting up the Affine Backgrounds</h2></div></div></div><p>
                libnds helps us once again by provide a nice <span class="ERROR">&lt;glossaryterm&gt;API&lt;/glossaryterm&gt;</span> for accessing the affine
                transformation matrix of a particular affine background. libnds
                provides access to a background's affine transformation matrix
                through four variables. <a href="#libnds_affine_bg_api" title="Figure 5.2. libnds Affine Background API">Figure 5.2, “libnds Affine Background API”</a>
                shows the names of these variables and which part of the affine
                transformation matrix they align with. 
            </p><div class="figure"><a id="libnds_affine_bg_api"></a><p class="title"><b>Figure 5.2. libnds Affine Background API</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/libnds_affine_bg_api.svg" alt="libnds Affine Background API" /></div></div></div><br class="figure-break" /><p>
                What we'll do now is add three backgrounds. We'll put a splash
                screen on the top physical screen, a starfield on the bottom
                physical screen, and a planet placed atop the starfield
                background. To do this, we'll use SUB_BG3 (although we could
                use SUB_BG2) for the splash screen and both backgrounds 2 and 3
                on the main screen for the planet and starfield respectively.
                In order to make sure the planet shows up above the starfield
                as opposed to below it, we give the planet a priority number
                less than that of the starfield's priority number. Relatively
                lower priority numbers place backgrounds relatively above other
                backgrounds. There are only four priority numbers per graphics
                engine that we can assign to backgrounds (priority numbers 0-3).
            </p><p>
                We'll now use that nice API libnds provides us for both the
                background control registers and the affine transformation
                matrix. Let's proceed to make a function called <code class="code"><code class="function">initBackgrounds</code></code>
                which will set up our affine backgrounds. Explanations of what
                is going on is the comments.
            </p><pre class="programlisting">
void initBackgrounds() {
    /*  Set up affine background 3 on main as a 16-bit color background */
    BG3_CR = BG_BMP16_256x256 |
             BG_BMP_BASE(0) | // The starting place in memory
             BG_PRIORITY(3); // A low priority

    /*  Set the affine transformation matrix for the main screen background 3
     *  to be the identity matrix.
     */
    BG3_XDX = 1 &lt;&lt; 8;
    BG3_XDY = 0;
    BG3_YDX = 0;
    BG3_YDY = 1 &lt;&lt; 8;

    /*  Place main screen background 3 at the origin (upper left of the screen)
     */
    BG3_CX = 0;
    BG3_CY = 0;


    /*  Set up affine background 2 on main as a 16-bit color background */
    BG2_CR = BG_BMP16_128x128 |
             BG_BMP_BASE(8) | // The starting place in memory
             BG_PRIORITY(2);  // A higher priority

    /*  Set the affine transformation matrix for the main screen background 3
     *  to be the identity matrix.
     */
    BG2_XDX = 1 &lt;&lt; 8;
    BG2_XDY = 0;
    BG2_YDX = 0;
    BG2_YDY = 1 &lt;&lt; 8;

    /*  Place main screen background 2 an interesting place
     */
    BG2_CX = -(SCREEN_WIDTH / 2 - 32) &lt;&lt; 8;
    BG2_CY = -32 &lt;&lt; 8;

    /*  Set up affine background 3 on sub as a 16-bit color background */
    SUB_BG3_CR = BG_BMP16_256x256 |
                 BG_BMP_BASE(0) | // The starting place in memory
                 BG_PRIORITY(3); // A low priority

    /*  Set the affine transformation matrix for the sub screen background 3
     *  to be the identity matrix.
     */
    SUB_BG3_XDX = 1 &lt;&lt; 8;
    SUB_BG3_XDY = 0;
    SUB_BG3_YDX = 0;
    SUB_BG3_YDY = 1 &lt;&lt; 8;

    /*
     *  Place main screen background 3 at the origin (upper left of the screen)
     */
    SUB_BG3_CX = 0;
    SUB_BG3_CY = 0;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533874"></a>Fixed Point Number Primer</h2></div></div></div><p>
                What's up with all those "&lt;&lt; 8" thingies? Those are fixed
                point numbers. The Nintendo DS expects many values to be in
                varying fixed point formats. A fixed point number is simply a
                way of specifying multiples of fractions to represent
                non-integer values. For example, if we use an integer variable
                to store a US Dollar amount, we might initially think we can
                only represent whole dollar values. However, if we decide to
                store US pennies in the integer as opposed to whole dollar
                values, we can all of a sudden represent fractions of US
                Dollars with our integer. We can have 1.21 US Dollars by saying
                we have 121 pennies.
            </p><p>
                Common notation for fixed point types looks like 1.31, 1.7.24,
                8.8, and etc. To interpret this notation, we read from right to
                left. First, we find the number of bits used to specify
                fractional parts. The next number will be the number of bits
                for whole number parts. And, if there is another number, it
                will usually indicate the sign of the number as being either
                positive or negative with one bit. <a href="#fixed_point" title="Figure 5.3. Integer variables can be used to represent&#10;                fractions.">Figure 5.3, “Integer variables can be used to represent
                fractions.”</a> illustrates the concept of fixed point
                numbers.
            </p><div class="figure"><a id="fixed_point"></a><p class="title"><b>Figure 5.3. Integer variables can be used to represent
                fractions.</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/fixed_point.svg" alt="Integer variables can be used to represent fractions." /></div></div></div><br class="figure-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2533953"></a>The Basics of DMA</h2></div></div></div><p>
                DMA stands for Direct Memory Access. DMA allows the reading and
                writing of memory independently of the CPU. The Nintendo DS has
                special, dedicated DMA hardware to do quick and moderately
                effcient moving of memory. DMA is not very efficient for memory
                fill operations, however, as the data to fill with needs to be
                read once for every write. Libnds provides us with a few
                functions to make use of the DMA hardware in the Nintendo DS.
            </p><p>
                Whenever you have the opportunity to use DMA, you should. It is
                always better to use DMA than to use a for loop to copy data.
                When using DMA to copy from main memory, do not forget to flush
                main memory before using DMA. Another issue to consider would
                be that in the middle of a DMA, the main CPUs are prevented
                from using certain memory hardware. This can cause awkward bugs with interrupt
                handling. For this reason, and <code class="code"><code class="function">swifastcopy</code></code> may be
                safer, and is not too much slower. The safest bet is always
                <code class="code"><code class="function">memcopy</code></code> and
                <code class="code"><code class="function">memset</code></code>, if you
                are running into some bugs.
            </p><p>
                The declaration of <code class="code"><code class="function">dmaCopyHalfWords</code></code>
                from libnds is as follows.
            </p><div class="funcsynopsis"><table border="0" summary="Function synopsis" cellspacing="0" cellpadding="0" style="padding-bottom: 1em"><tr><td><code class="funcdef">static inline void
                    <b class="fsfunc">dmaCopyHalfWords</b>(</code></td><td><var class="pdparam">uint8 channel</var><var class="pdparam">const void * source</var><var class="pdparam">void * dest</var><var class="pdparam">uint32 size</var><code>)</code>;</td><td> </td></tr></table><table border="0" summary="Function argument synopsis" cellspacing="0" cellpadding="0"><tr><td><code>
                        
                        
                        
                        </code> </td><td><code><var class="pdparam">uint8 channel</var><var class="pdparam">const void * source</var><var class="pdparam">void * dest</var><var class="pdparam">uint32 size</var>;</code></td></tr></table></div><p>
                In our program, we will use
                <code class="code"><code class="function">dmaCopyHalfWords</code></code> to
                load some graphics
                into memory. We use the function
                <code class="code"><code class="function">dmaCopyHalfWords</code></code>
                instead of
                <code class="code"><code class="function">dmaCopy</code></code>
                because it is more explicit as to
                how it is copying. We'll use the same channel (channel 3) that
                the ordinary <code class="code"><code class="function">dmaCopy</code></code> uses,
                though. It also let's us specify
                which DMA channel to use when copying. Let's start out by
                writing some functions to display our backgrounds. Since we've
                already set up the hardware to display the data in the desired
                manner, right after the copy we will get some nice images
                displayed on our screens. If we didn't set up our backgrounds
                first, we'd most likely get garbage on the screen until we
                eventually did set up the background control registers.
            </p><pre class="programlisting">
/* Select a low priority DMA channel to perform our background
 * copying. */
static const int DMA_CHANNEL = 3;

void displayStarField() {
    dmaCopyHalfWords(DMA_CHANNEL,
                     starFieldBitmap, /* This variable is generated for us by
                                       * grit. */
                     (uint16 *)BG_BMP_RAM(0), /* Our address for main
                                               * background 3 */
                     starFieldBitmapLen); /* This length (in bytes) is generated
                                           * from grit. */
}

void displayPlanet() {
    dmaCopyHalfWords(DMA_CHANNEL,
                     planetBitmap, /* This variable is generated for us by
                                    * grit. */
                     (uint16 *)BG_BMP_RAM(8), /* Our address for main
                                               * background 2 */
                     planetBitmapLen); /* This length (in bytes) is generated
                                        * from grit. */
}

void displaySplash() {
    dmaCopyHalfWords(DMA_CHANNEL,
                     splashBitmap, /* This variable is generated for us by
                                    * grit. */
                     (uint16 *)BG_BMP_RAM_SUB(0), /* Our address for sub
                                                   * background 3 */
                     splashBitmapLen); /* This length (in bytes) is generated
                                        * from grit. */
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534164"></a>Working with the Makefile</h2></div></div></div><p>
                The default template makefile will turn your graphic files into
                object files for linking into your program. Never include data
                as a header file.
            </p><p>
                The graphics must be in a lossless image format, such as gif,
                tif, bmp, or png in order to work with the provided template
                makefile. I prefer the png graphic format. Image conversion is
                usually done by a program called <span><strong class="command">grit</strong></span>. The
                provided template makefile will ask <span><strong class="command">grit</strong></span> to
                convert images in the <code class="filename">gfx</code> folder of your
                project root to a format ready for the Nintendo DS.
            </p><p>
                The provided template makefile, adapted from the default libnds
                template makefile, is a good base for most all projects. It
                will look in a folder called <code class="filename">gfx</code> (in the
                same directory as the makefile) for your graphics. If any are
                found, it uses a special bin2o rule to tell grit to turn your
                images into .o files, according to grit rule files (with the
                .grit files extension), which can be linked into your program.
                <span><strong class="command">grit</strong></span> will create a header file (.h) for your
                data. The name format for them works like so: if a file is
                called <code class="filename">orangeShuttle.png</code> the header file
                will be called <code class="filename">orangeShuttle.h</code>. Inside
                this header file will be a reference to the data in the .o,
                named orangeShuttleTiles and orangeShuttlePal or
                orangeShuttleBitmap, depending on how the grit file specifies
                which format to convert your image into. It will also include
                the length in bytes of the data references as
                orangeShuttleTilesLen and orangeShuttlePalLen or
                orangeShuttleBitmapLen.
            </p><p>
                For our project, we'll be putting the our graphic files and
                grit rule files into the <code class="filename">gfx</code> directory and
                having the makefile use <span><strong class="command">grit</strong></span> on them.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534271"></a>Gritty Crash Course</h2></div></div></div><p>
                With the emergence of the awesome and multi-platform tool,
                <span><strong class="command">grit</strong></span> there is no reason to not learn how to
                use it. It is now a standard tool in Nintendo DS and GBA
                development where aforeto there was no universal method of
                image conversion.
            </p><p>
                To use grit, we make a grit rule file. This file has the .grit
                file extension an contains important information telling grit
                how we want our image converted. You can learn about how grit
                works by reading its built-in help by running the command
                <span><strong class="command">grit</strong></span> with no parameters. I've also provided
                commented grit rule files for all images we will use in this
                manual. These make good examples and can help you get the hang
                of using grit.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534315"></a>Putting in the Star Fields</h2></div></div></div><p>
                Let's now put these functions into our main() function to get
                everything working together.
            </p><pre class="programlisting">
#include &lt;nds.h&gt;

#include "starField.h"
#include "planet.h"
#include "splash.h"

/* Other functions we've made are here. */

int main() {
    /*  Turn on the 2D graphics core. */
    powerON(POWER_ALL_2D);

    /*
     *  Set up interrupts.
     *
     *  We don't really get into what these do exactly at this point in the
     *  manual, but we still need to do them for now.
     */
    irqInit();
    irqSet(IRQ_VBLANK, 0);

    /*  Configure the VRAM and background control registers. */
    lcdMainOnBottom(); // Place the main screen on the bottom physical screen
    initVideo(); 
    initBackgrounds(); 

    /*  Display the backgrounds. */
    displayStarField(); 
    displayPlanet();
    displaySplash();

    return 0;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534363"></a>Compiling</h2></div></div></div><p>
                Check over your code, referring to the included examples if
                needed. Make sure you have the graphics files and the grit rule
                files in the <code class="filename">gfx</code> directory in your project
                directory. Bring up the command line and set your current
                working directory to the directory which contains the makefile
                for your project. Type <span><strong class="command">make</strong></span> and if all goes
                well, you'll have good success. See <a href="#chapter_5_screen_shot" title="Figure 5.4. The program should look like this when run.">Figure 5.4, “The program should look like this when run.”</a>. Copy your program to your DS
                using the method you have chosen.
            </p><div class="figure"><a id="chapter_5_screen_shot"></a><p class="title"><b>Figure 5.4. The program should look like this when run.</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/splash.png" alt="The program should look like this when run." /></div><div class="mediaobject"><img src="images/starfield_and_planet.png" alt="The program should look like this when run." /></div></div></div><br class="figure-break" /></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2534437"></a>Chapter 6. What is a sprite? How do I use them?</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2534443">Magical Fairies?</a></span></dt><dt><span class="sect1"><a href="#id2534462">The OAM</a></span></dt><dt><span class="sect1"><a href="#id2534481">Information About the Sprite Hardware</a></span></dt><dt><span class="sect1"><a href="#id2534510">How Sprites are Stored in Memory</a></span></dt><dt><span class="sect1"><a href="#id2534620">Sprite Attributes</a></span></dt><dt><span class="sect1"><a href="#id2534689">Updating the OAM</a></span></dt><dt><span class="sect1"><a href="#id2534738">Initializing the OAM</a></span></dt><dt><span class="sect1"><a href="#id2534796">Rotating Sprites</a></span></dt><dt><span class="sect1"><a href="#id2534866">Showing and Hiding Sprites</a></span></dt><dt><span class="sect1"><a href="#id2534943">Moving Sprites</a></span></dt><dt><span class="sect1"><a href="#id2534983">Setting Sprite Priorities</a></span></dt><dt><span class="sect1"><a href="#id2535031">Using the Sprites</a></span></dt><dt><span class="sect1"><a href="#id2535058">Setting up VRAM for Sprites</a></span></dt><dt><span class="sect1"><a href="#id2535133">Sprite Tile Addressing</a></span></dt><dt><span class="sect1"><a href="#id2535219">Loading in a Sprite</a></span></dt><dt><span class="sect1"><a href="#id2535573">What are assertions?</a></span></dt><dt><span class="sect1"><a href="#id2535639">Displaying the Sprites</a></span></dt><dt><span class="sect1"><a href="#id2535692">Compiling</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534443"></a>Magical Fairies?</h2></div></div></div><p>
                No, sprites are not magical fairies. It is a term in 2D
                graphics programming which refers to an image or animation. The
                Nintendo DS has dedicated hardware for dealing with sprites.
                This makes the system very useful for 2D. Most gaming systems
                do not have a 2D core, and all sprites and other 2D graphics
                have to be handled manually by painting 2D images on the side
                of a quad within 3D space.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534462"></a>The OAM</h2></div></div></div><p>
                The OAM manages all the sprites. This is an immense job, most
                of it done behind the scenes for us. After using it, you might
                think it magical. It's not as magical as it seems, however. OAM
                stands for Object Attribute Memory. It is the place in memory
                we use to keep track of and control our sprites. The OAM works
                with a SpriteEntry and a SpriteRotation struct to manage the
                attributes of our sprites.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534481"></a>Information About the Sprite Hardware</h2></div></div></div><p>
                On the Nintendo DS, we can have up to 128 sprites. Only 32 of
                those sprites can be affine transformed (rotated, scaled,
                skewed, etc.). We are also only allowed to address 1024
                different tiles to comprise all of our sprites, per engine.
                Sprites can be made of tiles that use 16 colors or of ones that
                use 256 colors. Tiles that use 256 colors are twice as large as
                tiles that use only 16 colors. Another advantage of using
                16-color sprites is the ability to use 16 different palettes.
                When using 256-color sprites, each sprite (and tile) must use
                the same palette. When using 16-color sprites, we can have one
                sprite use one 16-color palette and another sprite use a
                different 16-color palette, even though both use the same tile
                data. Games often use this trick to make different colored
                enemies that look the same. The sprites still use the same tile
                data, but they use different palettes.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534510"></a>How Sprites are Stored in Memory</h2></div></div></div><p>
                Sprites are broken into 8x8 pixel pieces. This is called
                tiling. When drawn to screen, the hardware pieces these tiles
                together, like a puzzle where the pieces have no distinguishing
                edges. There are two ways to tile sprites, 1D and 2D. In a 2D
                layout, the sprite memory is treated like a giant image from
                which sprite tiles are obtained by making a box the size of the
                sprite and placing it over the giant image. In a 1D layout, the
                sprites are layed out in a linear fashion, as discussed in
                <a href="#sprite_tile_layout" title="Figure 6.1. &#10;                    The upper text shows information as it would be on a&#10;                    non-tiled background. The lower text shows the same data,&#10;                    tiled, for use in tiled graphic modes.&#10;                ">Figure 6.1, “
                    The upper text shows information as it would be on a
                    non-tiled background. The lower text shows the same data,
                    tiled, for use in tiled graphic modes.
                ”</a>.
            </p><p>
                The conversion process is very similar to that for backgrounds.
                We simple make grit rule files that tell grit how we want our
                images converted, and it generates a .o and a header file for
                us. The grit rule files and image files go into the same place
                as background images, the <code class="filename">gfx&gt;</code> folder.
            </p><div class="figure"><a id="sprite_tile_layout"></a><p class="title"><b>Figure 6.1. 
                    The upper text shows information as it would be on a
                    non-tiled background. The lower text shows the same data,
                    tiled, for use in tiled graphic modes.
                </b></p><div class="figure-contents"><pre class="programlisting">
const u16 data[] = {
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0F0F, 0x0F0F, 0x0F0F, 0x0F0F, 0x0F0F, 0x0F0F, 0x0F0F, 0x0F0F,
0x2020, 0x2020, 0x2020, 0x2020, 0x2020, 0x2020, 0x2020, 0x2020,
0x2F2F, 0x2F2F, 0x2F2F, 0x2F2F, 0x2F2F, 0x2F2F, 0x2F2F, 0x2F2F,
0x4040, 0x4040, 0x4040, 0x4040, 0x4040, 0x4040, 0x4040, 0x4040,
0x4F4F, 0x4F4F, 0x4F4F, 0x4F4F, 0x4F4F, 0x4F4F, 0x4F4F, 0x4F4F,
0x6060, 0x6060, 0x6060, 0x6060, 0x6060, 0x6060, 0x6060, 0x6060,
0x6F6F, 0x6F6F, 0x6F6F, 0x6F6F, 0x6F6F, 0x6F6F, 0x6F6F, 0x6F6F,
0x8080, 0x8080, 0x8080, 0x8080, 0x8080, 0x8080, 0x8080, 0x8080,
0x8F8F, 0x8F8F, 0x8F8F, 0x8F8F, 0x8F8F, 0x8F8F, 0x8F8F, 0x8F8F,
0xA0A0, 0xA0A0, 0xA0A0, 0xA0A0, 0xA0A0, 0xA0A0, 0xA0A0, 0xA0A0,
0xAFAF, 0xAFAF, 0xAFAF, 0xAFAF, 0xAFAF, 0xAFAF, 0xAFAF, 0xAFAF,
0xC0C0, 0xC0C0, 0xC0C0, 0xC0C0, 0xC0C0, 0xC0C0, 0xC0C0, 0xC0C0,
0xCFCF, 0xCFCF, 0xCFCF, 0xCFCF, 0xCFCF, 0xCFCF, 0xCFCF, 0xCFCF,
0xE0E0, 0xE0E0, 0xE0E0, 0xE0E0, 0xE0E0, 0xE0E0, 0xE0E0, 0xE0E0,
0xEFEF, 0xEFEF, 0xEFEF, 0xEFEF, 0xEFEF, 0xEFEF, 0xEFEF, 0xEFEF};
const u16 data[] = {
0x0000, 0x0000, 0x0000, 0x0000, 0x0F0F, 0x0F0F, 0x0F0F, 0x0F0F,
0x2020, 0x2020, 0x2020, 0x2020, 0x2F2F, 0x2F2F, 0x2F2F, 0x2F2F,
0x4040, 0x4040, 0x4040, 0x4040, 0x4F4F, 0x4F4F, 0x4F4F, 0x4F4F,
0x6060, 0x6060, 0x6060, 0x6060, 0x6F6F, 0x6F6F, 0x6F6F, 0x6F6F,
0x0000, 0x0000, 0x0000, 0x0000, 0x0F0F, 0x0F0F, 0x0F0F, 0x0F0F,
0x2020, 0x2020, 0x2020, 0x2020, 0x2F2F, 0x2F2F, 0x2F2F, 0x2F2F,
0x4040, 0x4040, 0x4040, 0x4040, 0x4F4F, 0x4F4F, 0x4F4F, 0x4F4F,
0x6060, 0x6060, 0x6060, 0x6060, 0x6F6F, 0x6F6F, 0x6F6F, 0x6F6F,
0x8080, 0x8080, 0x8080, 0x8080, 0x8F8F, 0x8F8F, 0x8F8F, 0x8F8F,
0xA0A0, 0xA0A0, 0xA0A0, 0xA0A0, 0xAFAF, 0xAFAF, 0xAFAF, 0xAFAF,
0xC0C0, 0xC0C0, 0xC0C0, 0xC0C0, 0xCFCF, 0xCFCF, 0xCFCF, 0xCFCF,
0xE0E0, 0xE0E0, 0xE0E0, 0xE0E0, 0xEFEF, 0xEFEF, 0xEFEF, 0xEFEF,
0x8080, 0x8080, 0x8080, 0x8080, 0x8F8F, 0x8F8F, 0x8F8F, 0x8F8F,
0xA0A0, 0xA0A0, 0xA0A0, 0xA0A0, 0xAFAF, 0xAFAF, 0xAFAF, 0xAFAF,
0xC0C0, 0xC0C0, 0xC0C0, 0xC0C0, 0xCFCF, 0xCFCF, 0xCFCF, 0xCFCF,
0xE0E0, 0xE0E0, 0xE0E0, 0xE0E0, 0xEFEF, 0xEFEF, 0xEFEF, 0xEFEF};
                </pre></div></div><br class="figure-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534620"></a>Sprite Attributes</h2></div></div></div><p>
                Sprites have three attribute variables associated with them.
                With them, sprites can spin and flip and mosaic and perform all
                sorts of fun hardware effects. Each attribute is multi-purpose
                and requires some amount of bit twiddling and masking to
                achieve the affects we want. That is, it would if it weren't
                for this nice SpriteEntry union which libnds provides for us.
                In most cases, we will use this union to do what we'd like to
                with our sprites, but there are special cases where this is not
                possible.
            </p><p>
                We will cover how to update, initialize, and rotate using bit
                twiddling methods, as libnds doesn't yet provide ways of doing
                this otherwise. libnds provides the means to do other things
                that we'll be doing with sprites though, like move them, we'll
                be doing. We'll use the libnds API wherever possible. Let's
                write some functions to do each of those, in that order.
            </p><p>
                I provide you with a header file, located with the acompanying
                source at
                <code class="filename">code/chapter_6-sprites/include/sprites.h</code>
                that contains a collection of sprite related function
                declarations. We'll be working on the definitions for each of
                these functions together in a new file called
                <code class="filename">sprites.cpp</code>. Our first step will be to
                create a that new source code file. Put a new file called
                <code class="filename">sprites.cpp</code> into the
                <code class="filename">source</code> folder of your project directory.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534689"></a>Updating the OAM</h2></div></div></div><p>
                Instead of keeping track of things directly in the OAM, we'll
                manage a copy of the OAM in memory that we will copy over every
                frame using <code class="code"><code class="function">updateOAM</code></code>. The
                reason we do this is because writes to OAM are locked during
                all times but during vblank. We will wait for vblank to occur
                before copying our copy of the OAM into the actualy OAM.
            </p><p>
                Updating the OAM is very straightforward. First, we flush local
                memory (a must whenever performing a DMA operation). Then, we
                tell the OAM to look into the tOAM instance we will create
                later for information about each one of our sprites.
            </p><pre class="programlisting">
void updateOAM(tOAM * oam) {
    DC_FlushAll();
    dmaCopyHalfWords(SPRITE_DMA_CHANNEL,
                     oam-&gt;spriteBuffer,
                     OAM,
                     SPRITE_COUNT * sizeof(SpriteEntry));
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534738"></a>Initializing the OAM</h2></div></div></div><p>
                The first thing we do when initializing the OAM is to clear all
                the sprite data in the OAM. After that, we'll make a call to
                our afore written <code class="code"><code class="function">updateOAM</code></code> function.
            </p><pre class="programlisting">
void initOAM(tOAM * oam) {
    /*
     * For all 128 sprites on the DS, disable and clear any attributes they 
     * might have. This prevents any garbage from being displayed and gives 
     * us a clean slate to work with.
     */
    for (int i = 0; i &lt; SPRITE_COUNT; i++) {
        oam-&gt;spriteBuffer[i].attribute[0] = ATTR0_DISABLED;
        oam-&gt;spriteBuffer[i].attribute[1] = 0;
        oam-&gt;spriteBuffer[i].attribute[2] = 0;
    }
    for (int i = 0; i &lt; MATRIX_COUNT; i++) {
        /* If you look carefully, you'll see this is that affine trasformation
         * matrix again. We initialize it to the identity matrix, as we did
         * with backgrounds
         */
        oam-&gt;matrixBuffer[i].hdx = 1 &lt;&lt; 8;
        oam-&gt;matrixBuffer[i].hdy = 0;
        oam-&gt;matrixBuffer[i].vdx = 0;
        oam-&gt;matrixBuffer[i].vdy = 1 &lt;&lt; 8;
    }

    /* Be sure to wait for vblank before trying to update the OAM. */
    swiWaitForVBlank();
    updateOAM(oam);
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534796"></a>Rotating Sprites</h2></div></div></div><p>
                Let's get to spinning. This is a bit more difficult than what
                we've done before, but still fun. It's nice to not have to make
                a separate sprite for each rotation position the sprite will be
                presented in. However, doing so may be necessary for some
                applications as the Nintendo DS rotation won't always look as
                pretty as if the rotations had been done elsewhere.
            </p><p>
                The libnds's sin and cos lookup tables employ a 512 degree
                system. Humans usually use a 360 degree system or radians. The
                angle we'll work with in this function will be one that is part
                of the 512 degree system. You'll have to convert your radians
                or weird 360 degree value (Seriously, why 360? Silly
                Babylonians.) to the 512 degree system before using this
                function in order to see the results you are expecting.
            </p><p>
                We have to use a transformation derived from our time spent
                playing with an affine transformation matrix. The sprite's
                affine transformation matrix is used slightly differently from
                the background affine transformation matrix. If you have a
                background in linear algebra, I’d recommend reading up on this
                portion of the hardware at <a href="http://www.coranac.com/tonc/text/affine.htm" target="_top">http://www.coranac.com/tonc/text/affine.htm</a>.
            </p><pre class="programlisting">
void rotateSprite(SpriteRotation * spriteRotation, u16 angle) {
    s16 s = SIN[angle &amp; SPRITE_ANGLE_MASK] &gt;&gt; 4;
    s16 c = COS[angle &amp; SPRITE_ANGLE_MASK] &gt;&gt; 4;
    
    spriteRotation-&gt;hdx = c;
    spriteRotation-&gt;hdy = s;
    spriteRotation-&gt;vdx = -s;
    spriteRotation-&gt;vdy = c;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534866"></a>Showing and Hiding Sprites</h2></div></div></div><p>
                Up until now, we haven't used the fancy SpriteEntry union
                included in libnds. It allows us to avoid thinking about bit
                twiddling and masking in most cases. In the case of showing and
                hiding sprites, we still need to be thinking about these bits
                due to an oddity in the Nintendo DS hardware: the hiding bit of
                a sprite (bit 9 of sprite attribute 0) is also the double bound
                bit of a sprite if the sprite is an affine sprite (bit 8 of
                sprite attribute 0). Follow along with the comments and code as
                we formulate a solution to writing a function which shows and
                hides all kinds of sprites.
            </p><pre class="programlisting">
void setSpriteVisibility(SpriteEntry * spriteEntry, bool hidden, bool affine,
                         bool doubleBound) {
    if (hidden) {
        /*
         * Make the sprite invisible.
         * 
         * An affine sprite cannot be hidden. We have to turn it into a
         * non-affine sprite before we can hide it. To hide any sprite, we must
         * set bit 8 and clear bit 9. For non-affine sprites, this is a bit
         * redundant, but it is faster than a branch to just set it regardless
         * of whether or not it is already set.
         */
        spriteEntry-&gt;isRotoscale = false; // Bit 9 off
        spriteEntry-&gt;isHidden = true; // Bit 8 on
    } else {
        /* Make the sprite visible.*/
        if (affine) {
            /* Again, keep in mind that affine sprites cannot be hidden, so
             * enabling affine is enough to show the sprite again. We also need
             * to allow the user to get the double bound flag in the sprite
             * attribute. If we did not, then our sprite hiding function would
             * not be able to properly hide and restore double bound sprites.
             * We enable bit 9 here because we want an affine sprite.
             */
            spriteEntry-&gt;isRotoscale = true;

            /* The double bound flag only acts as the double bound flag when
             * the sprite is an affine sprite. At all other times, it acts as
             * the sprite invisibility flag. We only enable bit 8 here if we want
             * a double bound sprite. */
            spriteEntry-&gt;rsDouble = doubleBound;
        } else {
            /* Bit 9 (the affine flag) will already be off here, so we don't
             * need to clear it. However, bit 8 (the sprite invisibility flag)
             * will need to be cleared. */
            spriteEntry-&gt;isHidden = false;
        }
    }
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534943"></a>Moving Sprites</h2></div></div></div><p>
                Now for some real fun. Moving sprites in hardware, and not
                having to worry about clipping, buffers, or anything, is such a
                wonderful feeling. To move a sprite, we simply change the
                SpriteEntry properties posX and posY. This is a case where we
                don't have to think much about the underlying arrangement of
                this information. The libnds union SpriteEntry describes the
                organization of data to the compiler for us and the compiler
                then figures out the best way to operate on that data; the
                compiler does the bit twiddling and masking for us. Since this
                is so simple, we don't even need to write a function to do it
                for us. So just take note of what we do here and remember it
                for later; you don't have to write a function for it, but if
                you want to I'd recommend making it an inline function.
            </p><pre class="programlisting">
/* This is what we'd do if we wanted to move a sprite. */
spriteEntry-&gt;posX = 0;
spriteEntry-&gt;posY = 0;
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2534983"></a>Setting Sprite Priorities</h2></div></div></div><p>
                The ability to set a sprites priorty is essential when dealing
                with multiple sprites, as we will be doing. As such, we'll now
                discuss sprite priorities and how to set them.
            </p><p>
                A sprite, like a background, has a priorty which determines how
                the sprite will appear with respect to other sprites and to
                backgrounds. A sprite with the same number priorty as a
                background will appear above it. A sprite with a lower priorty
                number than another sprite will appear above that other sprite.
                There are four priorities per graphics engine available for
                sprites, similar to background priorities.
            </p><p>  
                To set the sprite priority, we'll simply set the SpriteEntry
                property objPriority to one of four different values, depending
                on which priority we wish to assign: OBJPRIORITY_0,
                OBJPRIORITY_1, OBJPRIORITY_2, or OBJPRIORITY_3. The following
                code listing shows an example of what this looks like.
            </p><pre class="programlisting">
spriteEntry-&gt;objPriority = OBJPRIORITY_3;
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535031"></a>Using the Sprites</h2></div></div></div><p>
                Now that our sprites.cpp file is finished, let's get on to how
                sprites are stored in memory, how to load them, and so forth.
                So put away your sprites.cpp file into the source directory of
                your home folder and let's get back into our
                <code class="filename">main.cpp</code> file.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535058"></a>Setting up VRAM for Sprites</h2></div></div></div><p>
                We'll need to make a place for our sprite data to live in VRAM.
                Since we will be using sprites on the main graphics engine, we
                can use VRAM bank E for our sprites. VRAM bank E is smaller
                than the other VRAM banks we've dealt with so far, as it is
                only 64 KB in size. However, this is more than enough to store
                1024 unique 16-color tiles.
            </p><p>
                In our <code class="code"><code class="function">initVideo</code></code>, we need
                to map VRAM bank E for use with sprites on the main graphics
                engine. Then, we need to tell the main engine to enable sprites
                of the tiling style we want. We will use 1D tiled sprites. The
                resulting initVideo function, post-modifications, is presented
                below .
            </p><pre class="programlisting">
void initVideo() {
    /*
     *  Map VRAM to display a background on the main and sub screens.
     * 
     *  The vramSetMainBanks function takes four arguments, one for each of the
     *  major VRAM banks. We can use it as shorthand for assigning values to
     *  each of the VRAM bank's control registers.
     *
     *  We map banks A and B to main screen  background memory. This gives us
     *  256KB, which is a healthy amount for 16-bit graphics.
     *
     *  We map bank C to sub screen background memory.
     *
     *  We map bank D to LCD. This setting is generally used for when we aren't
     *  using a particular bank.
     *
     *  We map bank E to main screen sprite memory (aka object memory).
     */
    vramSetMainBanks(VRAM_A_MAIN_BG_0x06000000,
                     VRAM_B_MAIN_BG_0x06020000,
                     VRAM_C_SUB_BG_0x06200000,
                     VRAM_D_LCD);

    vramSetBankE(VRAM_E_MAIN_SPRITE);

    /*  Set the video mode on the main screen. */
    videoSetMode(MODE_5_2D | // Set the graphics mode to Mode 5
                 DISPLAY_BG2_ACTIVE | // Enable BG2 for display
                 DISPLAY_BG3_ACTIVE | // Enable BG3 for display
                 DISPLAY_SPR_ACTIVE | // Enable sprites for display
                 DISPLAY_SPR_1D       // Enable 1D tiled sprites
                 );

    /*  Set the video mode on the sub screen. */
    videoSetModeSub(MODE_5_2D | // Set the graphics mode to Mode 5
                    DISPLAY_BG3_ACTIVE); // Enable BG3 for display
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535133"></a>Sprite Tile Addressing</h2></div></div></div><p>
                We'll be using the same memory alignment (boundary) as the GBA
                uses for our sprites. Tile VRAM addresses must be aligned to 32
                bytes. If you feel shorted by this, since you can't use all
                1024 addressable tiles when using 256 color tiles, for
                instance, then you can look up how to use other alignments at
                <a href="http://nocash.emubase.de/gbatek.htm#dsvideoobjs" target="_top">http://nocash.emubase.de/gbatek.htm#dsvideoobjs</a>.
                You'll have to set REG_DISPCNT (via videoSetMode) with a value
                defined in <code class="filename">libnds/include/nds/arm9/video.h</code>
                akin to DISPLAY_SPR_1D_SIZE_XXX (the default, and the method
                the GBA and we use, is DISPLAY_SPR_1D_SIZE_32).
            </p><p>
                To compute the address to copy tiles to, we basically need to
                know two things: the memory alignment we are using and the tile
                numbers we want to assign data to. Using the formula from
                Martin Korth's GBATEK, "TileVramAddress = TileNumber *
                BoundaryValue", and libnds's SPRITE_GFX define we can compute
                the address of any tile as follows.
            </p><pre class="programlisting">
static const int BOUNDARY_VALUE = 32; /* This is the default boundary value
                                       * (can be set in REG_DISPCNT) */
static const int OFFSET_MULTIPLIER = BOUNDARY_VALUE /
                                     sizeof(SPRITE_GFX[0]);
uint16 * tileVramAddress = &amp;SPRITE_GFX[shuttle-&gt;tileIdx *
                                           OFFSET_MULTIPLIER];
            </pre><p>
                We usually want to copy more than one tile into vram at a time,
                however. Luckily, when converting images to sprites with grit,
                it will tell us the length in bytes of our tile data for that
                sprite. After we have the length in bytes, we can use
                dmaCopyHalfwords (which uses byte lengths for copying) to copy
                the tile data into VRAM. We can also calculate how many tiles
                an image uses from its length in bytes by diving the length in
                bytes by how many bytes a tile takes up. In our case, as we'll
                be using 16-color tiles, a tile (8x8 pixels) takes up 16 bytes.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535219"></a>Loading in a Sprite</h2></div></div></div><p>
                Now, to see a sprite in action. Let's load in the orangeShuttle
                graphic and the moon graphic. Make a new function called <code class="code"><code class="function">initSprites</code></code>. Place
                it after the <code class="code"><code class="function">initBackgrounds</code></code>
                function. Make sure to include
                <code class="filename">orangeShuttle.h</code> and
                <code class="filename">moon.h</code> now. They contain information about
                our sprites as generated by grit. 
            </p><p>
                I've also create a new struct type called "SpriteInfo". This
                struct contains information about sprites that aren't
                explicitly contained in the SpriteEntry struct. We'll be using
                it to help us manage our information about sprites better.
            </p><div class="procedure"><a id="id2535273"></a><p class="title"><b>Procedure 6.1. To Create a Sprite</b></p><ol type="1"><li><p>
                        We'll begin by filling in our SpriteInfo struct for the
                        sprite. Each sprite will have its own SpriteInfo
                        struct. The first thing we need to do is assign an OAM
                        ID to the sprite. This number will help us keep track
                        of which OAM entry our sprite is associated with. We'll
                        also use it to compute other offsets, although we don't
                        have to use it for that purpose in many cases.
                    </p></li><li><p>
                        Assign the width, height, and angle of the sprite.
                    </p></li><li><p>
                        Select an OAM entry to associate with this sprite.
                    </p></li><li><p>
                        Configure attribute 0.
                    </p></li><li><p>
                        Configure attribute 1.
                    </p></li><li><p>
                        Configure attribute 2.
                    </p></li><li><p>
                        Copy tile data to VRAM.
                    </p></li><li><p>
                        Copy the palette data to VRAM.
                    </p></li></ol></div><p>
                We'll just follow these steps twice when writing the
                initSprites function for our sprites. You can follow along with
                the comments and the code below.
            </p><pre class="programlisting">
void initSprites(tOAM * oam, SpriteInfo *spriteInfo) {
    /*  Define some sprite configuration specific constants.
     * 
     *  We will use these to compute the proper index into memory for certain
     *  tiles or palettes.
     *
     *  OFFSET_MULTIPLIER is calculated based on the following formula from
     *  GBATEK (http://nocash.emubase.de/gbatek.htm#dsvideoobjs):
     *      TileVramAddress = TileNumber * BoundaryValue
     *  Since SPRITE_GFX is a uint16*, the compiler will increment the address
     *  it points to by 2 for each change in 1 of the array index into
     *  SPRITE_GFX. (The compiler does pointer arithmetic.)
     */
    static const int BYTES_PER_16_COLOR_TILE = 32;
    static const int COLORS_PER_PALETTE = 16;
    static const int BOUNDARY_VALUE = 32; /* This is the default boundary value
                                           * (can be set in REG_DISPCNT) */
    static const int OFFSET_MULTIPLIER = BOUNDARY_VALUE /
                                         sizeof(SPRITE_GFX[0]);

    /* Keep track of the available tiles */
    int nextAvailableTileIdx = 0;

    /* Create the ship sprite. */
    static const int SHUTTLE_OAM_ID = 0;
    assert(SHUTTLE_OAM_ID &lt; SPRITE_COUNT);
    SpriteInfo * shuttleInfo = &amp;spriteInfo[SHUTTLE_OAM_ID];
    SpriteEntry * shuttle = &amp;oam-&gt;spriteBuffer[SHUTTLE_OAM_ID];

    /* Initialize shuttleInfo */
    shuttleInfo-&gt;oamId = SHUTTLE_OAM_ID;
    shuttleInfo-&gt;width = 64;
    shuttleInfo-&gt;height = 64;
    shuttleInfo-&gt;angle = 462;
    shuttleInfo-&gt;entry = shuttle;

    /*
     *  Configure attribute 0. 
     *
     *  OBJCOLOR_16 will make a 16-color sprite. We specify that we want an
     *  affine sprite (via isRotoscale) here because we would like to rotate
     *  the ship.
     */
    shuttle-&gt;posY = SCREEN_HEIGHT / 2 - shuttleInfo-&gt;height;
    shuttle-&gt;isRotoscale = true;
    /* This assert is a check to see a matrix is available to store the affine
     * transformation matrix for this sprite. Of course, you don't have to have
     * the matrix id match the affine id, but if you do make them match, this
     * assert can be helpful. */
    assert(!shuttle-&gt;isRotoscale || (shuttleInfo-&gt;oamId &lt; MATRIX_COUNT));
    shuttle-&gt;rsDouble = false;
    shuttle-&gt;objMode = OBJMODE_NORMAL;
    shuttle-&gt;isMosaic = false;
    shuttle-&gt;colMode = OBJCOLOR_16;
    shuttle-&gt;objShape = OBJSHAPE_SQUARE;

    /*
     *  Configure attribute 1.
     *
     *  rsMatrixId refers to the loation of affine transformation matrix. We
     *  set it to a location computed with a macro. OBJSIZE_64, in our case
     *  since we are making a square sprite, creates a 64x64 sprite.
     */
    shuttle-&gt;posX = SCREEN_WIDTH / 2 - shuttleInfo-&gt;width * 2 +
                    shuttleInfo-&gt;width / 2;
    shuttle-&gt;rsMatrixIdx = ATTR1_ROTDATA(shuttleInfo-&gt;oamId);
    shuttle-&gt;objSize = OBJSIZE_64;

    /* 
     *  Configure attribute 2.
     * 
     *  Configure which tiles the sprite will use, which priority layer it will
     *  be placed onto, which palette the sprite should use, and whether or not
     *  to show the sprite.
     */
    shuttle-&gt;tileIdx = nextAvailableTileIdx;
    nextAvailableTileIdx += orangeShuttleTilesLen / BYTES_PER_16_COLOR_TILE;
    shuttle-&gt;objPriority = OBJPRIORITY_0;
    shuttle-&gt;objPal = shuttleInfo-&gt;oamId;

    /* Rotate the sprite */
    rotateSprite(&amp;oam-&gt;matrixBuffer[shuttleInfo-&gt;oamId],
                 shuttleInfo-&gt;angle);

    /*************************************************************************/

    /* Create the moon sprite. */
    static const int MOON_OAM_ID = 1;
    assert(MOON_OAM_ID &lt; SPRITE_COUNT);
    SpriteInfo * moonInfo = &amp;spriteInfo[MOON_OAM_ID];
    SpriteEntry * moon = &amp;oam-&gt;spriteBuffer[MOON_OAM_ID];

    /* Initialize moonInfo */
    moonInfo-&gt;oamId = MOON_OAM_ID;
    moonInfo-&gt;width = 32;
    moonInfo-&gt;height = 32;
    moonInfo-&gt;angle = 462;
    moonInfo-&gt;entry = moon;

    /*
     *  Configure attribute 0.
     *
     *  OBJCOLOR_16 will make a 16-color sprite. We won't specify that we want
     *  an affine sprite here because we don't want one this time.
     */
    moon-&gt;posY = SCREEN_WIDTH / 2 + moonInfo-&gt;height / 2;
    moon-&gt;isRotoscale = false;
    /* This assert is a check to see a matrix is available to store the affine
     * transformation matrix for this sprite. Of course, you don't have to have
     * the matrix id match the affine id, but if you do make them match, this
     * assert can be helpful. */
    assert(!moon-&gt;isRotoscale || (moonInfo-&gt;oamId &lt; MATRIX_COUNT));
    moon-&gt;isHidden = false;
    moon-&gt;objMode = OBJMODE_NORMAL;
    moon-&gt;isMosaic = false;
    moon-&gt;colMode = OBJCOLOR_16;
    moon-&gt;objShape = OBJSHAPE_SQUARE;

    /*
     * Configure attribute 1.
     *
     * OBJSIZE_32 will create a sprite of size 32x32, since we are making a
     * square sprite. Since we are using a non-affine sprite, attribute 1
     * doesn't have an rsMatrixIdx anymore. Instead, it has the ability to flip
     * the sprite vertically or horizontally.
     */
    moon-&gt;posX = SCREEN_WIDTH / 2 + moonInfo-&gt;width + moonInfo-&gt;width / 2;
    moon-&gt;hFlip = false;
    moon-&gt;vFlip = false;
    moon-&gt;objSize = OBJSIZE_32;

    /* 
     *  Configure attribute 2.
     * 
     *  Configure which tiles the sprite will use, which priority layer it will
     *  be placed onto, which palette the sprite should use, and whether or not
     *  to show the sprite.
     */
    moon-&gt;tileIdx = nextAvailableTileIdx;
    nextAvailableTileIdx += moonTilesLen / BYTES_PER_16_COLOR_TILE;
    moon-&gt;objPriority = OBJPRIORITY_2;
    moon-&gt;objPal = moonInfo-&gt;oamId;

    /*************************************************************************/

    /* Copy over the sprite palettes */
    dmaCopyHalfWords(SPRITE_DMA_CHANNEL,
                     orangeShuttlePal,
                     &amp;SPRITE_PALETTE[shuttleInfo-&gt;oamId *
                                     COLORS_PER_PALETTE],
                     orangeShuttlePalLen);
    dmaCopyHalfWords(SPRITE_DMA_CHANNEL,
                     moonPal,
                     &amp;SPRITE_PALETTE[moonInfo-&gt;oamId * COLORS_PER_PALETTE],
                     moonPalLen);

    /* Copy the sprite graphics to sprite graphics memory */
    dmaCopyHalfWords(SPRITE_DMA_CHANNEL,
                     orangeShuttleTiles,
                     &amp;SPRITE_GFX[shuttle-&gt;tileIdx * OFFSET_MULTIPLIER],
                     orangeShuttleTilesLen);
    dmaCopyHalfWords(SPRITE_DMA_CHANNEL,
                     moonTiles,
                     &amp;SPRITE_GFX[moon-&gt;tileIdx * OFFSET_MULTIPLIER],
                     moonTilesLen);
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535573"></a>What are assertions?</h2></div></div></div><p>
                In the above code, you'll find some things that look like
                function calls to a function called <code class="code"><code class="function">assert</code></code>. These aren't
                actually function calls, but macro expansions. You'll have to
                include <code class="filename">assert.h</code> in order to use them.
            </p><pre class="programlisting">
#include &lt;assert.h&gt;
            </pre><p>
                The assert macro allows the programmer to make assumptions
                about what is going on in the code. To use them, you just place
                some kind of "fact" in between the paranthesis. Whenever this
                assumption fails, the program will quit. Assertions are
                evaluated at runtime.
            </p><p>
                Assertions help you avoid bugs developing obscure later on
                since they'll stop them right where something first goes wrong.
                Assertions are a good thing and should be used often.
            </p><p>
                When you release a production version of your software, the
                assertions can be removed from your code by the preprocessor.
                To do this with a GNU compiler, like the ones we are using, you
                simply set NDEBUG.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535639"></a>Displaying the Sprites</h2></div></div></div><p>
                In our main function, we now need to initialize our copy of the
                OAM, create the structs which hold our sprite data, make a call
                to the <code class="code"><code class="function">initSprites</code></code> function
                we just created, and then update the OAM by copying our OAM
                copy to OAM.
            </p><pre class="programlisting">
int main() {
    /*  Turn on the 2D graphics core. */
    powerON(POWER_ALL_2D);

    /*
     *  Set up interrupts.
     *
     *  We don't really get into what these do exactly at this point in the
     *  manual, but we still need to do them for now.
     */
    irqInit();
    irqSet(IRQ_VBLANK, 0);

    /*
     *  Configure the VRAM and background control registers.
     *
     *  Place the main screen on the bottom physical screen. Then arrange the
     *  VRAM banks. Next, confiure the background control registers.
     */
    lcdMainOnBottom();
    initVideo();
    initBackgrounds();

    /* Set up a few sprites. */
    SpriteInfo spriteInfo[SPRITE_COUNT];
    tOAM *oam = new tOAM();
    initOAM(oam);
    initSprites(oam, spriteInfo);

    /* Display the backgrounds. */
    displayStarField();
    displayPlanet();
    displaySplash();

    /*
     *  Update the OAM.
     *
     *  We have to copy our copy of OAM data into the actual
     *  OAM during VBlank (writes to it are locked during
     *  other times).
     */
    swiWaitForVBlank();
    updateOAM(oam);

    return 0;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535692"></a>Compiling</h2></div></div></div><p>
                Before you get to compiling, you may want to look at the top of
                your <code class="filename">main.cpp</code> file and verify that you are
                including all the proper files. There are a lot of files to
                include now, so it is easy to lose track of which ones we need.
                (I probably even forgot to let you know about some of them.)
            </p><pre class="programlisting">
#include &lt;nds.h&gt;
#include &lt;assert.h&gt;
#include "sprites.h"

/* Backgrounds */
#include "starField.h"
#include "planet.h"
#include "splash.h"
/* Sprites */
#include "orangeShuttle.h"
#include "moon.h"
            </pre><p>
                If all goes well, you’ll compile with no problems and the
                output will look as in <a href="#chapter_6_screen_shot" title="Figure 6.2. Output with both backgrounds and a sprite.">Figure 6.2, “Output with both backgrounds and a sprite.”</a>.
            </p><div class="figure"><a id="chapter_6_screen_shot"></a><p class="title"><b>Figure 6.2. Output with both backgrounds and a sprite.</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/splash.png" alt="Output with both backgrounds and a sprite." /></div><div class="mediaobject"><img src="images/starfield_and_orange_shuttle.png" alt="Output with both backgrounds and a sprite." /></div></div></div><br class="figure-break" /></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2535783"></a>Chapter 7. Basic Game Mechanics Applied to the Space Shooter Genre</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2535790">The Importance of Object Oriented Programming</a></span></dt><dt><span class="sect1"><a href="#id2535810">The Ship Class</a></span></dt><dt><span class="sect1"><a href="#id2535955">Making the Ship Class</a></span></dt><dt><span class="sect1"><a href="#id2535986">The Constructor</a></span></dt><dt><span class="sect1"><a href="#id2536004">Acceleration</a></span></dt><dt><span class="sect1"><a href="#id2536067">Moving the Ship</a></span></dt><dt><span class="sect1"><a href="#id2536095">Reversing the Ship's Direction</a></span></dt><dt><span class="sect1"><a href="#id2536124">Rotating the Ship</a></span></dt><dt><span class="sect1"><a href="#id2536153">Getting the Ship's Position</a></span></dt><dt><span class="sect1"><a href="#id2536178">Getting the Ship's Angle</a></span></dt><dt><span class="sect1"><a href="#id2536267">Linking the Ship into our Program</a></span></dt><dt><span class="sect1"><a href="#id2536331">Creating the Main Game Loop</a></span></dt><dt><span class="sect1"><a href="#id2536436">Compiling</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535790"></a>The Importance of Object Oriented Programming</h2></div></div></div><p>
                Object oriented programming (OOP) is essential to making good
                games on a modern system. Although it is very much possible
                without object oriented programming, OOP is an incredible tool
                that greatly improves code reusability, readability,
                modularization, and abstraction. It makes the programmer's job
                a lot easier. Also, due to modularization, collaborating on
                projects with your friends or coworkers is easily ten fold
                easier.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535810"></a>The Ship Class</h2></div></div></div><p>
                The first thing we'll make is a Ship class. This class will
                encapsulate all the properties and functionality of any ship in
                an easy to use and understand format. Think of things a ship
                can do, on a high level. What should come to mind is the
                ability to turn both ways, shoot weapons, accelerate, move at a
                given velocity (coasting), and maybe some more things if you
                are creative enough. What properties of a ship can you come up
                with? Perhaps turning speed, thrust, mass, maximum speed,
                velocity, position, shields? Well, after you are done
                brainstorming, the next step is to write out the functionality
                and properties we need to put into our Ship class. You could
                make a table, as in <a href="#ship_properties_and_functions" title="Table 7.1. Table of Ship properties and functionality.">Table 7.1, “Table of Ship properties and functionality.”</a>, or draw some
                diagrams on a piece of paper. Either way, you want to make sure
                your ideas all get onto some physical paper before you begin
                coding.
            </p><div class="table"><a id="ship_properties_and_functions"></a><p class="title"><b>Table 7.1. Table of Ship properties and functionality.</b></p><div class="table-contents"><table summary="Table of Ship properties and functionality." border="1"><colgroup><col /><col /></colgroup><thead><tr><th>Properties</th><th>Functionality</th></tr></thead><tbody><tr><td>shipHeight</td><td>accelerate</td></tr><tr><td>shipWidth</td><td>moveShip</td></tr><tr><td>position</td><td>turnClockwise</td></tr><tr><td>velocity</td><td>turnCounterClockwise</td></tr><tr><td>angle</td><td>getPosition</td></tr><tr><td>turnSpeed</td><td>reverseTurn</td></tr><tr><td>thrust</td><td>getAngle</td></tr><tr><td>maxSpeed</td><td class="auto-generated"> </td></tr><tr><td>mass</td><td class="auto-generated"> </td></tr></tbody></table></div></div><br class="table-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535955"></a>Making the Ship Class</h2></div></div></div><p>
                I have provided a skeleton framework file for you to write your
                class in. It is all set and ready for you to implement in the
                <code class="filename">ship.cpp</code> file. The header file,
                <code class="filename">ship.h</code> is also included. On your own, with
                your own classes in the future, you should always make a
                skeleton framework class to work from. It makes implementation
                straightforward and you do not have to worry about the
                semantics of setting up a class so much.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2535986"></a>The Constructor</h2></div></div></div><p>
                I have provided you with a simple constructor and private
                initialization method method. These are often mundane things to
                make. In fact, the compiler will automatically make the
                constructor, copy constructor, and operator= methods for you if
                you don't explicitly make them. Feel free to modify the default
                values in the initializers to try out different effects of
                changing the ship properties.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536004"></a>Acceleration</h2></div></div></div><p>
                Acceleration is probably one of the most important things your
                ships can do. To accelerate, we simply increase our velocity by
                a certain increment, that being the thrust capability of the
                ship, in the angle we are headed. Here is where some simple
                trigonometry comes into play. Since our velocity is stored as a
                two dimensional vecotr (x and y component), we have to shadow
                our thrust vector onto each direction. We do this we multiply
                the thrust by sin(angle) for our x component, and by
                -cos(angle) for the y direction. Next, after we have computed
                the increment for both x and y, we add them onto our current
                velocity, making sure we don’t go over the ship's maximum
                speed.
            </p><pre class="programlisting">
void Ship::accelerate() {
    float incX = thrust * sin(angle);
    float incY = -(thrust * cos(angle));

    //the following method of speed limitation is not accurate, traveling
    //diagonally is faster than straight, which is not the desired limitation
    //a more accurate method is needed at a later time

    velocity.x += incX;
    //make sure can't go too fast in x direction
    if (velocity.x &gt; maxSpeed) {
        velocity.x = maxSpeed;
    }
    if (velocity.x &lt; -maxSpeed) {
        velocity.x = -maxSpeed;
    }

    velocity.y += incY;
    //make sure can't go too fast in y direction
    if (velocity.y &gt; maxSpeed) {
        velocity.y = maxSpeed;
    }
    if (velocity.y &lt; -maxSpeed) {
        velocity.y = -maxSpeed;
    }
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536067"></a>Moving the Ship</h2></div></div></div><p>
                This one is incredibly easy thanks to the Nintendo DS hardware.
                All we have to do is increment our position by our velocity. The
                hardware takes care of any wrapping or offscreen issues.
            </p><pre class="programlisting">
void Ship::moveShip() {
    //move the ship
    position.x += velocity.x;
    position.y += velocity.y;

    //hw does wrap around for us, so we don't have to have any of that sort of
    //logic in here
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536095"></a>Reversing the Ship's Direction</h2></div></div></div><p>
                This one took me a while to figure out, even though it's just one
                line, but it's very useful. We can turn the ship around, not a
                180 per se, but simply pointing into the opposite direction of
                our current velocity. This will get the angle of our velocity
                with respect to 0 degrees, and then will do a 180 from that
                angle.
            </p><pre class="programlisting">
void Ship::reverseTurn() {
    angle = (2 * PI) - atan2(velocity.x, velocity.y);
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536124"></a>Rotating the Ship</h2></div></div></div><p>
                Rotating the ship is also quite simple. We just increment or by
                ship’s turning speed depending on which direction we wish to
                turn.
            </p><pre class="programlisting">
void Ship::turnClockwise() {
      angle += turnSpeed;
}
void Ship::turnCounterClockwise() {
      angle -= turnSpeed;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536153"></a>Getting the Ship's Position</h2></div></div></div><p>
                Return the ship’s position.
            </p><pre class="programlisting">
MathVector2D&lt;float&gt; Ship::getPosition() {
      return position;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536178"></a>Getting the Ship's Angle</h2></div></div></div><p>
                This one is a bit more tricky and involved. I suppose I should
                start by explaining that a Nintendo DS circle has 512 degrees.
                It doesn’t actually have 512 degrees, nor does a Nintendo DS
                even know what a circle is, but it is easy to understand the
                hardware a bit better when we think of it this way. I will say,
                however, that the reason for the 512 degrees is due to libnds’s
                built-in look up tables for the sin and cos functions. Having
                only 360 entries in your lookup table would be a waste of space
                when it takes just as many bits to index into a 360 entry table
                as it does a 512 entry one. More entries allow finer accuracy.
                In order for the Nintendo DS to know how to rotate our sprites,
                we have to convert the internally stored radian angle value to
                a 512 degree system. This is an easy conversion.
            </p><p>
                The first step is to convert to a 360 degree system, as you must
                have learned in junior high school. This is done by multiplying
                the radian value by 180/π. The 180 part is half the number of
                degrees in a circle. So, in a 512 degree system we can convert
                by multiplying the radian value by 256/π. Lastly, just return
                that value as an integer. (The hardware does not have any
                floating point, so when rotating our sprites, we use a fixed
                point value disguised as an ordinary integer.)
            </p><p>
                Then, we make a function to return a converted angle value, for
                whenever we need it.
            </p><pre class="programlisting">
int Ship::radToDeg512(float rad) {
      return (int)(rad * (256/PI));
}
int Ship::getAngleDeg512() {
      return radToDeg512(angle);
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536267"></a>Linking the Ship into our Program</h2></div></div></div><p>
                We now need to create an instance of the ship in our main
                function. Creating an instance of a class, known as an object,
                is quite simple, as you can see below. We just have to create
                the Ship object and then assign a SpriteEntry to it.
            </p><p>
                We should also do something nifty with our new class so that we
                can verify that what we wrote is working. Let's make the ship
                move around on its own by telling the ship to trust ten times.
            </p><pre class="programlisting">
int main() {
    /*  Turn on the 2D graphics core. */
    powerON(POWER_ALL_2D);

    /*
     *  Set up interrupts.
     *
     *  We don't really get into what these do exactly at this point in the
     *  manual, but we still need to do them for now.
     */
    irqInit();
    irqSet(IRQ_VBLANK, 0);

    /*
     *  Configure the VRAM and background control registers.
     *
     *  Place the main screen on the bottom physical screen. Then arrange the
     *  VRAM banks. Next, confiure the background control registers.
     */
    lcdMainOnBottom();
    initVideo();
    initBackgrounds();

    /* Set up a few sprites. */
    SpriteInfo spriteInfo[SPRITE_COUNT];
    tOAM *oam = new tOAM();
    initOAM(oam);
    initSprites(oam, spriteInfo);

    /* Display the backgrounds. */
    displayStarField();
    displayPlanet();
    displaySplash();

    static const int SHUTTLE_OAM_ID = 0;
    SpriteEntry * shipEntry = &amp;oam-&gt;spriteBuffer[SHUTTLE_OAM_ID];
    SpriteRotation * shipRotation = &amp;oam-&gt;matrixBuffer[SHUTTLE_OAM_ID];
    Ship * ship = new Ship(&amp;spriteInfo[SHUTTLE_OAM_ID]);

    /* Accelerate the ship for a little while to make it move. */
    for (int i = 0; i &lt; 10; i++) {
        ship-&gt;accelerate();
    }

    /*
     *  Update the OAM.
     *
     *  We have to copy our copy of OAM data into the actual
     *  OAM during VBlank (writes to it are locked during
     *  other times).
     */
    swiWaitForVBlank();
    updateOAM(oam);

    return 0;
}
        </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536331"></a>Creating the Main Game Loop</h2></div></div></div><p>
                The previous code isn't very exciting, since we never update
                the OAM more than once. We need to begin the creation of what
                is referred to as the game loop. We won't be fully implementing
                it in this chapter, since a major component of it will be
                missing until we discover input on the Nintendo DS.
            </p><p>
                The game loop has at least three major components. The first
                thing any game loop should do is to collect input from the
                outside world. We won't be doing that in this chapter, however.
                The next component of the game loop is updating the game state.
                Based on inputs the game received in the previous frame (to the
                one we'll render next) and the passing of time, the game state
                will change (if anything interesting is happening). The final
                component of the game loop is the rendering component. In our
                case, we have to update the OAM to let it know of the changes
                that occured in the game state and that it needs to reflect
                those changes.
            </p><p>
                Now that we know what a game loop is, it's time for us to start
                creating one to run our program. The first thing we want to
                happen in our game loop is for the game state to be updated.
                This is because we don't have any input to collect yet. We tell
                our ship to move at it's current velocity. This will change
                the ship’s position. Then we update the sprite attributes with
                new information about our ship, as some properties of the ship
                have now changed (i.e. its position). Finally, we call a
                function that will make sure our program does not exceed 60fps
                (speed of the graphics on the Nintendo DS) by waiting for
                vblank, and then we update the OAM, telling it that we changed
                some attributes on the sprites and it needs to handle that.
            </p><pre class="programlisting">
    for (;;) {
        /* Update the game state. */
        ship-&gt;moveShip();

        /* Update sprite attributes. */
        MathVector2D&lt;float&gt; position = ship-&gt;getPosition();
        shipEntry-&gt;posX = (int)position.x;
        shipEntry-&gt;posY = (int)position.y;
        rotateSprite(shipRotation, ship-&gt;getAngleDeg512());

        /*
         *  Update the OAM.
         *
         *  We have to copy our copy of OAM data into the actual OAM during
         *  VBlank (writes to it are locked during other times).
         */
        swiWaitForVBlank();
        updateOAM(oam);
    }

    return 0;
}
            </pre><p>
                The OAM really shines through here. The all powerful Nintendo
                DS hardware, an incredible masterpiece, will rotate and move
                our ship with very little effort on our part. In hindsight, all
                we have done is flip a few bits in a few registers in a
                structured manner, and our ship comes to life. Incredible.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536436"></a>Compiling</h2></div></div></div><p>
                Verify that you are including all the files you need to include
                now, before compiling.
            </p><pre class="programlisting">
#include &lt;nds.h&gt;
#include &lt;assert.h&gt;
#include "sprites.h"
#include "ship.h"

/* Backgrounds */
#include "starField.h"
#include "planet.h"
#include "splash.h"
/* Sprites */
#include "orangeShuttle.h"
#include "moon.h"
            </pre><p>
                Everything should compile for you fine at this point if you wish
                to play around with your new class. However, in the next
                chapter we will cover how to get Nintendo DS input to affect
                the Ship. Be ready for it, we're going to have some major fun.
            </p><div class="mediaobject"><img src="images/orange_shuttle.png" /></div></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2536488"></a>Chapter 8. Nintendo DS Input Systems</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2536494">Overview</a></span></dt><dt><span class="sect1"><a href="#id2536520">Key Input</a></span></dt><dt><span class="sect1"><a href="#id2536822">Touch!</a></span></dt><dt><span class="sect1"><a href="#id2536885">Writing an Input Updating Function</a></span></dt><dt><span class="sect1"><a href="#id2536929">Writing an Input Handling Function</a></span></dt><dt><span class="sect1"><a href="#id2537045">Creating the Main Game Loop, Again</a></span></dt><dt><span class="sect1"><a href="#id2537179">Compiling</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536494"></a>Overview</h2></div></div></div><p>
                The Nintendo DS has many different user input systems,
                including buttons, touch screen, and a microphone. Most video
                game systems only have buttons and an analog stick or two.
                While the Nintendo DS does not have an analog stick, it does
                have an amazing touch screen which has millions of different
                creative uses. We will only cover the touch screen and buttons,
                though. If you wish to learn more about the microphone, I'd
                recommend reading, although a bit outdated, the only microphone
                resource I know of <a href="http://www.double.co.nz/nintendo_ds/nds_develop9.html" target="_top">http://www.double.co.nz/nintendo_ds/nds_develop9.html</a>.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536520"></a>Key Input</h2></div></div></div><p>
                libnds provides us with a very nice abstraction for key input.
                Instead of having to AND registers with cryptic masks to
                discover which keys we are pressing, we simply call <code class="code"><code class="function">scanKeys</code></code>, then check
                one of three input functions, <code class="code"><code class="function">keysDown()</code></code>, <code class="code"><code class="function">keysHeld</code></code>, or <code class="code"><code class="function">keysUp</code></code>. In order to
                see which keys have been recently pressed, use <code class="code"><code class="function">keysDown</code></code>. To see
                which keys are currently held, use <code class="code"><code class="function">keysHeld</code></code>. To see
                which keys have just been released, use <code class="code"><code class="function">keysUp</code></code>. libnds
                provides us with defines for some key masks as well. How they
                are set up is explained in <a href="#libnds_key_defines" title="Table 8.1. libnds Key Defines">Table 8.1, “libnds Key Defines”</a>.
            </p><div class="table"><a id="libnds_key_defines"></a><p class="title"><b>Table 8.1. libnds Key Defines</b></p><div class="table-contents"><table summary="libnds Key Defines" border="1"><colgroup><col /><col /><col /></colgroup><thead><tr><th>Key Define</th><th>Mask
                            Bit</th><th>Associated Input</th></tr></thead><tbody><tr><td>KEY_A</td><td>1 &lt;&lt;
                            0</td><td>A Button</td></tr><tr><td>KEY_B</td><td>1 &lt;&lt;
                            1</td><td>B Button</td></tr><tr><td>KEY_SELECT</td><td>1 &lt;&lt;
                            2</td><td>Select Button</td></tr><tr><td>KEY_START</td><td>1 &lt;&lt;
                            3</td><td>Start Button</td></tr><tr><td>KEY_RIGHT</td><td>1 &lt;&lt;
                            4</td><td>Right D-pad</td></tr><tr><td>KEY_LEFT</td><td>1 &lt;&lt;
                            5</td><td>Left D-pad</td></tr><tr><td>KEY_UP</td><td>1 &lt;&lt;
                            6</td><td>Up D-pad</td></tr><tr><td>KEY_DOWN</td><td>1 &lt;&lt;
                            7</td><td>Down D-pad</td></tr><tr><td>KEY_R</td><td>1 &lt;&lt;
                            8</td><td>R Button</td></tr><tr><td>KEY_L</td><td>1 &lt;&lt;
                            9</td><td>L Button</td></tr><tr><td>KEY_X</td><td>1 &lt;&lt;
                            10</td><td>X Button</td></tr><tr><td>KEY_Y</td><td>1 &lt;&lt;
                            11</td><td>Y Button</td></tr><tr><td>KEY_TOUCH</td><td>1 &lt;&lt;
                            12</td><td>Pen Touching Screen (no
                            coordinates)</td></tr><tr><td>KEY_LID</td><td>1 &lt;&lt;
                            13</td><td>Lid shutting (useful for
                            sleeping)</td></tr></tbody></table></div></div><br class="table-break" /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536822"></a>Touch!</h2></div></div></div><p>
                Utada Hikaru wants to touch it. You have to code it. Let's go!
            </p><p>
                The touch screen a big part of what makes the Nintendo DS
                awesome. The libnds API for using it is cake easy too. We'll be
                ready for Utada Hikaru in no time. Whenever you want to read the
                current touch location, simply call the function <code class="code"><code class="function">touchReadXY</code></code>. This
                function returns a struct that contains the x and y coordinate
                of the touch. You access it like so.
            </p><pre class="programlisting">
/* To read from the touch screen, we can do this stuff. */
touchPosition touch = touchReadXY();
touch-&gt;px; // This contains the x pixel location.
touch-&gt;py; // This contains the y pixel location.
            </pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">What is the IPC?</h3><p>
                    You may see code that uses something called the IPC to
                    interact with the touch screen. Use of the IPC struct is
                    deprecated. This means that you shouldn't use it and should
                    not depend on it being there in the future. The method we
                    use to read values from the touch screen does not use the
                    IPC struct and is safe for future use.
                </p></div></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536885"></a>Writing an Input Updating Function</h2></div></div></div><p>
                Now that we know a bit about how input is laid out on the
                Nintendo DS, let's write a function in our
                <code class="filename">main.cpp</code> to collect the input for us.
                We'll call it <code class="code"><code class="function">updateInput</code></code>. We'll
                use this function as the first thing we call in our complete
                game loop.
            </p><pre class="programlisting">
void updateInput(touchPosition * touch) {
    // Update the key registers with current values.
    scanKeys();

    // Update the touch screen values.
    *touch = touchReadXY();
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2536929"></a>Writing an Input Handling Function</h2></div></div></div><p>
                This function will be part of our game state updating game loop
                component. It will react to outside input and modify the game
                state accordingly. As such, it will have to know about and be
                able to modify the game state. We'll pass the game state to it
                as function parameters. Let's call the function <code class="code"><code class="function">handleInput</code></code>.
            </p><p>
                First, we want the ship to accelerate when we press up. To do
                this, we detect when the Nintendo DS has the up key on the
                D-pad held (which included the initial down press) and
                accelerate the ship if so. The up key will constantly read as
                held, so long as it is held. Reading the input does not affect
                the keys register. We'll do similar things for each of the
                other keys. See if you can tell what each key does from the
                code listing below.
            </p><pre class="programlisting">
void handleInput(Ship * ship, MathVector2D&lt;int&gt; * moonPos,
                 SpriteInfo * moonInfo, touchPosition * touch) {

    /* Handle up and down parts of D-Pad. */
    if (keysHeld() &amp; KEY_UP) {
        //accelerate ship
        ship-&gt;accelerate();
    } else if (keysHeld() &amp; KEY_DOWN) {
        //reverse ship direction
        ship-&gt;reverseTurn();
    }
    
    /* Handle left and right parts of D-Pad. */
    if (keysHeld() &amp; KEY_LEFT) {
        //rotate counter clockwise
        ship-&gt;turnCounterClockwise();
    } else if (keysHeld() &amp; KEY_RIGHT) {
        //rotate clockwise
        ship-&gt;turnClockwise();
    }

    /*
     *  Handle the touch screen.
     *  
     *  This is basically some fancy pants junk to enable grabbing and moving
     *  of the moon. It isn't essential to know how this code works to
     *  understand how to reach values from the touch screen, but it was cool
     *  enough that I wanted to put it in the case study.
    */
    static MathVector2D&lt;int&gt; moonGrip;
    if (keysDown() &amp; KEY_TOUCH) {
        /* Record the grip */
        moonGrip.x = touch-&gt;px;
        moonGrip.y = touch-&gt;py;
    } else if (keysHeld() &amp; KEY_TOUCH) {
        int newX = moonPos-&gt;x + touch-&gt;px - moonGrip.x;
        int newY = moonPos-&gt;y + touch-&gt;py - moonGrip.y;

        /* Prevent dragging off the screen */
        if (newX &lt; 0) {
            moonPos-&gt;x = 0;
        } else if (newX &gt; (SCREEN_WIDTH - moonInfo-&gt;width)) {
            moonPos-&gt;x = SCREEN_WIDTH - moonInfo-&gt;width;
        } else {
            moonPos-&gt;x = newX;
        }
        if (newY &lt; 0) {
            moonPos-&gt;y = 0;
        } else if (newY &gt; (SCREEN_HEIGHT - moonInfo-&gt;height)) {
            moonPos-&gt;y = SCREEN_HEIGHT - moonInfo-&gt;height;
        } else {
            moonPos-&gt;y = newY;
        }

        /* Record the grip again. */
        moonGrip.x = touch-&gt;px;
        moonGrip.y = touch-&gt;py;
    }
}
            </pre><p>
                As you've noticed, having that Ship class made input handling
                extremely easy. Our keys will directly affect various
                properties of the ship as we press them. This is really
                amazing, but the true miracle is yet to come.
            </p><p>
                As for the moon, since we didn't make one class for it, the
                code came together a little more messily. We also had to pass
                two parameters to the <code class="code"><code class="function">handleInput</code></code> function
                to represent the moon portion of the game state instead of one.
                If we had wanted to be more clean, we could have even produced
                a game state struct that contained all the game state and all
                operations on it in one place.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537045"></a>Creating the Main Game Loop, Again</h2></div></div></div><p>
                Let's check back in on our <code class="code"><code class="function">main</code></code> function now.
                We need to make some adjustments to our game loop since we've
                now added the ability to collect input and to react to input.
                The first thing we now want to happen in our game loop is for
                the key registers and read touch screen coordinates to get
                updated. We make a call to updateInput and it all happens for
                us. Next, we handle the input we just received by calling our
                recently created <code class="code"><code class="function">handleInput</code></code>
                function, passing in our game state so that it can change it
                for us. Everything else is as before. 
            </p><pre class="programlisting">
int main() {
    /*  Turn on the 2D graphics core. */
    powerON(POWER_ALL_2D);

    /*
     *  Set up interrupts.
     *
     *  We don't really get into what these do exactly at this point in the
     *  manual, but we still need to do them for now.
     */
    irqInit();
    irqSet(IRQ_VBLANK, 0);

    /*
     *  Configure the VRAM and background control registers.
     *
     *  Place the main screen on the bottom physical screen. Then arrange the
     *  VRAM banks. Next, confiure the background control registers.
     */
    lcdMainOnBottom();
    initVideo();
    initBackgrounds();

    /* Set up a few sprites. */
    SpriteInfo spriteInfo[SPRITE_COUNT];
    tOAM *oam = new tOAM();
    initOAM(oam);
    initSprites(oam, spriteInfo);

    /* Display the backgrounds. */
    displayStarField();
    displayPlanet();
    displaySplash();

    /*************************************************************************/

    /* Keep track of the touch screen coordinates */
    touchPosition touch;

    /* Make the ship object */
    static const int SHUTTLE_AFFINE_ID = 0;
    SpriteEntry * shipEntry = &amp;oam-&gt;spriteBuffer[SHUTTLE_AFFINE_ID];
    SpriteRotation * shipRotation = &amp;oam-&gt;matrixBuffer[SHUTTLE_AFFINE_ID];
    Ship * ship = new Ship(&amp;spriteInfo[SHUTTLE_AFFINE_ID]);

    /* Make the moon */
    static const int MOON_AFFINE_ID = 1;
    SpriteEntry * moonEntry = &amp;oam-&gt;spriteBuffer[MOON_AFFINE_ID];
    SpriteInfo * moonInfo = &amp;spriteInfo[MOON_AFFINE_ID];
    MathVector2D&lt;int&gt; * moonPos = new MathVector2D&lt;int&gt;();
    moonPos-&gt;x = moonEntry-&gt;posX;
    moonPos-&gt;y = moonEntry-&gt;posY;

    for (;;) {
        /* Update the game state. */
        updateInput(&amp;touch);
        handleInput(ship, moonPos, moonInfo, &amp;touch);
        ship-&gt;moveShip();

        /* Update ship sprite attributes. */
        MathVector2D&lt;float&gt; position = ship-&gt;getPosition();
        shipEntry-&gt;posX = (int)position.x;
        shipEntry-&gt;posY = (int)position.y;
        rotateSprite(shipRotation, ship-&gt;getAngleDeg512());
        /* Update moon sprite attributes. */
        moonEntry-&gt;posX = (int)moonPos-&gt;x;
        moonEntry-&gt;posY = (int)moonPos-&gt;y;

        /*
         *  Update the OAM.
         *
         *  We have to copy our copy of OAM data into the actual OAM during
         *  VBlank (writes to it are locked during other times).
         */
        swiWaitForVBlank();
        updateOAM(oam);
    }

    return 0;
}
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537179"></a>Compiling</h2></div></div></div><p>
                Again, we should double check that we have all the
                proper includes before compiling.
            </p><pre class="programlisting">
#include &lt;nds.h&gt;
#include &lt;assert.h&gt;
#include "sprites.h"
#include "ship.h"

/* Backgrounds */
#include "starField.h"
#include "planet.h"
#include "splash.h"
/* Sprites */
#include "orangeShuttle.h"
#include "moon.h"
            </pre><p>
                Now we can control our ship with the D-Pad. What fun! The game
                should now appear as in <a href="#chapter_8_screen_shot" title="Figure 8.1. Flying around in the Orange Shuttle.">Figure 8.1, “Flying around in the Orange Shuttle.”</a>. Now if only we had some
                aliens to kill…
            </p><div class="figure"><a id="chapter_8_screen_shot"></a><p class="title"><b>Figure 8.1. Flying around in the Orange Shuttle.</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/splash.png" alt="Flying around in the Orange Shuttle." /></div><div class="mediaobject"><img src="images/starfield_with_moving_orange_shuttle.png" alt="Flying around in the Orange Shuttle." /></div></div></div><br class="figure-break" /></div></div><div class="chapter" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title"><a id="id2537262"></a>Chapter 9. What about the sounds?</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="sect1"><a href="#id2537267">A Sound Theory</a></span></dt><dt><span class="sect1"><a href="#id2537310">The Hardware</a></span></dt><dt><span class="sect1"><a href="#id2537335">Making the Sounds</a></span></dt><dt><span class="sect1"><a href="#id2537399">Using the Sounds</a></span></dt><dt><span class="sect1"><a href="#id2537435">Getting Down with the Code</a></span></dt><dt><span class="sect1"><a href="#id2537624">Wait, What's Going on Here?</a></span></dt><dt><span class="sect1"><a href="#id2537669">The Need for Inter-processor Communication</a></span></dt><dt><span class="sect1"><a href="#id2537694">Compiling</a></span></dt></dl></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537267"></a>A Sound Theory</h2></div></div></div><p>
                Sounds are essential in any game. Our little project should be
                no exception. Sounds bring life to various elements in the
                game, such as space ships, weapon systems, rain, sword
                clashing, car engines, and so forth.
            </p><p>
                Many games don’t need music. For instance, a game with the
                programmer’s or game designer’s favorite song may annoy many
                players who have different tastes of music. Instead, give the
                player the option to listen to their own music, on their own
                audio equipment. Not to mention, music is costly in data size.
            </p><p>
                Sound eﬀects on the other hand, are quite useful. A word of
                warning, however, a game with bad sounds (scratchy, annoying,
                too repetitive, etc.) is worse than a silent game. Take care
                when engineering sounds for your game.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537310"></a>The Hardware</h2></div></div></div><p>
                The Nintendo DS has amazing sound hardware. We will only be
                able to scratch the surface of it, and even still, we won’t
                leave any scratch marks. The Nintendo DS has 16 channels to
                play sounds, numbered 0 through 15. Channels 8-15 are special
                channels. All channels can play ADPCM or PCM sounds, while 8-13
                are the only channels that can play PSG sounds and 14-15 the
                only that can generate noise. We will only be experimenting
                with PCM sounds.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537335"></a>Making the Sounds</h2></div></div></div><p>
                To play our sounds, we need to convert them into a PCM format
                that the DS will understand. The format we will use is 8-bit
                signed 22050Hz raw audio. You can experiment with other
                combinations if you'd like, but in the interest of keeping this
                manual simple we'll just be using the aforementioned format.
            </p><p>
                There are a myriad of programs our there to do sound conversion
                for us, but I will present the most universal method of sound
                conversion: the open source program SoX. SoX stands for Sound
                eXchange. It is available for Linux, Macintosh OS X, and
                Windows. I have included pre-compiled versions for Mac OS X
                PPC, Mac OS X x86, and Windows. For Linux, just compile the
                included SoX source.
            </p><p>
                To use SoX, simple convert your file as shown below. You can
                practice with my included audio file “thrust.aif ”. The relevant
                command line options work as follows: -b 8-bit, -s signed, -r
                22050 22050Hz sample rate. SoX knows to turn your sound into a
                .raw by reading the file extension on the output ﬁlename. Keep
                in mind since raw sounds have no headers, to somehow label them
                with their formatting information. I use the ﬁlename to do
                this, as you can see.
            </p><pre class="screen">
                <code class="prompt">patater@patater.com:~$</code><span><strong class="command">sox
                sounds/thrust.aif -bsr 22050
                data/thrust_1_22050_8_s.raw</strong></span>
            </pre></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537399"></a>Using the Sounds</h2></div></div></div><p>
                The makefile I've included with my manual has a custom bin2o
                rule for creating .o files from .raw files. There is really
                nothing special about it. It does the same thing that the .bin
                bin2o rule does. The libnds default makefiles require you to
                explicitly specify the file types you want to be processed.
            </p><p>
                After the makefile processes the raw sound file, the header for
                it will look like so
                <code class="filename">thrust_1_22050_8_s_raw.h</code> and will be
                located in the build directory.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537435"></a>Getting Down with the Code</h2></div></div></div><p>
                Now it's ﬁnally time for some code. Libnds simpliﬁes sound
                playing quite a bit. It provides a struct called
                "TransferSoundData" that we can use to encapsulate our sound.
                In a way, it acts as a header to let the DS know how to handle
                it. libnds will handle the transfer of the sound to the ARM7
                (the only processor that can control the sound hardware),
                although it is a bit inefficient, frumpy (and yes, for those of
                you who don’t know, libnds is a girl), and limited. It will
                serve our purposes for now, as a springboard into more advanced
                forms of sound. Enough with the chatter, here's some code for
                our <code class="filename">main.cpp</code>.
            </p><pre class="programlisting">
void handleInput(Ship * ship, MathVector2D&lt;int&gt; * moonPos,
                 SpriteInfo * moonInfo, TransferSoundData * soundData,
                 touchPosition * touch) {

    /* Handle up and down parts of D-Pad. */
    if (keysDown() &amp; KEY_UP) {
        // Play our sound only when the button is initially pressed
        playSound(soundData);
    }
    if (keysHeld() &amp; KEY_UP) {
        //accelerate ship
        ship-&gt;accelerate();
    } else if (keysHeld() &amp; KEY_DOWN) {
        //reverse ship direction
        ship-&gt;reverseTurn();
    }
    
    /* Handle left and right parts of D-Pad. */
    if (keysHeld() &amp; KEY_LEFT) {
        //rotate counter clockwise
        ship-&gt;turnCounterClockwise();
    } else if (keysHeld() &amp; KEY_RIGHT) {
        //rotate clockwise
        ship-&gt;turnClockwise();
    }

    /* Handle the touch screen. */
    static MathVector2D&lt;int&gt; moonGrip;
    if (keysDown() &amp; KEY_TOUCH) {
        /* Record the grip */
        moonGrip.x = touch-&gt;px;
        moonGrip.y = touch-&gt;py;
    } else if (keysHeld() &amp; KEY_TOUCH) {
        int newX = moonPos-&gt;x + touch-&gt;px - moonGrip.x;
        int newY = moonPos-&gt;y + touch-&gt;py - moonGrip.y;

        /* Prevent dragging off the screen */
        if (newX &lt; 0) {
            moonPos-&gt;x = 0;
        } else if (newX &gt; (SCREEN_WIDTH - moonInfo-&gt;width)) {
            moonPos-&gt;x = SCREEN_WIDTH - moonInfo-&gt;width;
        } else {
            moonPos-&gt;x = newX;
        }
        if (newY &lt; 0) {
            moonPos-&gt;y = 0;
        } else if (newY &gt; (SCREEN_HEIGHT - moonInfo-&gt;height)) {
            moonPos-&gt;y = SCREEN_HEIGHT - moonInfo-&gt;height;
        } else {
            moonPos-&gt;y = newY;
        }

        /* Record the grip again. */
        moonGrip.x = touch-&gt;px;
        moonGrip.y = touch-&gt;py;
    }
}

int main() {
    /*  Turn on the 2D graphics core. */
    powerON(POWER_ALL_2D);

    /*
     *  Set up interrupts.
     *
     *  We don't really get into what these do exactly at this point in the
     *  manual, but we still need to do them for now.
     */
    irqInit();
    irqSet(IRQ_VBLANK, 0);

    /*
     *  Configure the VRAM and background control registers.
     *
     *  Place the main screen on the bottom physical screen. Then arrange the
     *  VRAM banks. Next, confiure the background control registers.
     */
    lcdMainOnBottom();
    initVideo();
    initBackgrounds();

    /* Set up a few sprites. */
    SpriteInfo spriteInfo[SPRITE_COUNT];
    tOAM *oam = new tOAM();
    initOAM(oam);
    initSprites(oam, spriteInfo);

    /* Display the backgrounds. */
    displayStarField();
    displayPlanet();
    displaySplash();

    /*************************************************************************/

    /* Keep track of the touch screen coordinates */
    touchPosition touch;

    /* Make the ship object */
    static const int SHUTTLE_AFFINE_ID = 0;
    SpriteEntry * shipEntry = &amp;oam-&gt;spriteBuffer[SHUTTLE_AFFINE_ID];
    SpriteRotation * shipRotation = &amp;oam-&gt;matrixBuffer[SHUTTLE_AFFINE_ID];
    Ship * ship = new Ship(&amp;spriteInfo[SHUTTLE_AFFINE_ID]);

    /* Make the moon */
    static const int MOON_AFFINE_ID = 1;
    SpriteEntry * moonEntry = &amp;oam-&gt;spriteBuffer[MOON_AFFINE_ID];
    SpriteInfo * moonInfo = &amp;spriteInfo[MOON_AFFINE_ID];
    MathVector2D&lt;int&gt; * moonPos = new MathVector2D&lt;int&gt;();
    moonPos-&gt;x = moonEntry-&gt;posX;
    moonPos-&gt;y = moonEntry-&gt;posY;

    /*  Set up sound data.*/
    TransferSoundData * thrust_sound = new TransferSoundData();
    thrust_sound-&gt;data = thrust_1_22050_8_s_raw;
    thrust_sound-&gt;len = thrust_1_22050_8_s_raw_size;
    thrust_sound-&gt;rate = 22050; //22050Hz Sample Rate
    thrust_sound-&gt;vol = 127; //Volume can be from 0 to 127
    thrust_sound-&gt;pan = 64; //Sound comes equally from both speakers (0-127, left to right)
    thrust_sound-&gt;format = 1; //1 - 8bit, 0 - 16bit

    for (;;) {
        /* Update the game state. */
        updateInput(&amp;touch);
        handleInput(ship, moonPos, moonInfo, thrust_sound, &amp;touch);
        ship-&gt;moveShip();

        /* Update ship sprite attributes. */
        MathVector2D&lt;float&gt; position = ship-&gt;getPosition();
        shipEntry-&gt;posX = (int)position.x;
        shipEntry-&gt;posY = (int)position.y;
        rotateSprite(shipRotation, ship-&gt;getAngleDeg512());
        /* Update moon sprite attributes. */
        moonEntry-&gt;posX = (int)moonPos-&gt;x;
        moonEntry-&gt;posY = (int)moonPos-&gt;y;

        /*
         *  Update the OAM.
         *
         *  We have to copy our copy of OAM data into the actual OAM during
         *  VBlank (writes to it are locked during other times).
         */
        swiWaitForVBlank();
        updateOAM(oam);
    }

    return 0;
}
            </pre><p>
                In summary, we simply set up our sound in the
                <code class="code"><code class="function">main</code></code> function,
                modified the <code class="code"><code class="function">handleInput</code></code> function
                to accept a sound pointer, and had the <code class="code"><code class="function">handleInput</code></code> function
                play our sound whenever the up key is held.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537624"></a>Wait, What's Going on Here?</h2></div></div></div><p>
                Now, for an explanation of what libnds is doing behind the
                scenes. A pointer to your sound data in shared memory (iwram)
                is given to the arm7 from the arm9 via the IPC. If the pointer
                is null, then no sound will be played. If the pointer is not
                null, the arm7 ﬁnds an open sound channel. If any channels are
                open, it reads the header information from your
                TransferSoundData struct and then calls an internal function,
                startSound, which plays the sound for us.
            </p><p>
                The startSound function is not very ﬂexible (nor is the
                TransferSoundData struct). The sound can only be 8-bit or
                16-bit. We have no way of signaling the arm7 that we want the
                sound to loop, unfortunately. We also have no way of telling
                the sound to stop playing (which is extremely unfortunate). If
                we wanted these very useful capabilities, we’d have to create a
                nice inter-processor communication system.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537669"></a>The Need for Inter-processor Communication</h2></div></div></div><p>
                The need for a standard inter-processor communication system is
                real. Dekutree has written the presumably first one for the
                Nintendo DS. Chris Double used Dekutree's interprocessor
                communication model in his tutorials. Tobias Weyand, the
                creator of NitroTracker and the DS Sampling Keyboard, also used
                Dekutree's interprocessor communication model. Many programmers
                prefer to use the FIFO (a special queue for inter-processor
                communication built into the Nintendo DS hardware). I will
                address both of these methods and present a nice abstraction
                that will allow the programmer to choose either method
                (according to their needs and opinions) in a later edition of
                this manual.
            </p></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537694"></a>Compiling</h2></div></div></div><p>
                Check your includes.
            </p><pre class="programlisting">
#include &lt;nds.h&gt;
#include &lt;assert.h&gt;
#include "sprites.h"
#include "ship.h"

/* Backgrounds */
#include "starField.h"
#include "planet.h"
#include "splash.h"
/* Sprites */
#include "orangeShuttle.h"
#include "moon.h"
/* Sounds */
#include "thrust_1_22050_8_s_raw.h"
            </pre><p>
                This is the ﬁnal iteration of the Orange Spaceship demo that we
                will cover in this edition of the manual. Compile it and enjoy
                the fruits of your labors. Mmm, tasty. You should hear a nice
                sound when you press the thrust button. The game output should
                now look like the screen shots in <a href="#chapter_9_screen_shot" title="Figure 9.1. Flying around in the Orange Shuttle, with sound!">Figure 9.1, “Flying around in the Orange Shuttle, with sound!”</a>.
            </p><div class="figure"><a id="chapter_9_screen_shot"></a><p class="title"><b>Figure 9.1. Flying around in the Orange Shuttle, with sound!</b></p><div class="figure-contents"><div class="mediaobject"><img src="images/splash.png" alt="Flying around in the Orange Shuttle, with sound!" /></div><div class="mediaobject"><img src="images/starfield_with_moving_orange_shuttle.png" alt="Flying around in the Orange Shuttle, with sound!" /></div></div></div><br class="figure-break" /></div></div><div class="section" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537784"></a>Postface</h2></div></div></div><p>
            I hope you've enjoyed reading this manual as much as I've enjoyed
            writing it. I hope it has helped you to learn the basics of
            Nintendo DS programming, and if not, that it has pointed you in the
            correct direction. I wish you luck in all your future projects and
            endeavors.
        </p><p>
            Feel free to contact me <a href="mailto:jaeder@patatersoft.info" target="_top">mailto:jaeder@patatersoft.info</a>, if you need any help or
            have corrections or suggestions.
        </p></div><div class="section" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537810"></a>Acknowledgements</h2></div></div></div><p>
            I'd like to offer special thanks to all those who have taught me
            these past few years about Nintendo DS programming. I apologize if
            I've left anyone off the list who has helped me. Special thanks to:
        </p><div class="itemizedlist"><ul type="disc"><li><p>John Haugeland</p></li><li><p>Martin Korth</p></li><li><p>Dave Murphy</p></li><li><p>Liran Nuna</p></li><li><p>Thorsten Lemke</p></li><li><p>Tobias Weyand</p></li><li><p>Shaun Taylor</p></li><li><p>Bryant Poffenberger</p></li><li><p>Hollis Jacobsen</p></li><li><p>Jeff Katz</p></li><li><p>James Zawacki</p></li><li><p>Michael Noland</p></li><li><p>Jasper Vijn</p></li><li><p>Jason Rogers</p></li><li><p>Christopher Double</p></li><li><p>Matt Luckett</p></li><li><p>Mathias Onisseit</p></li></ul></div></div><div class="section" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="id2537960"></a>About the Author</h2></div></div></div><p>
            Jaeden Amero is currently an Electrical Engineering student at
            Brigham Young University in Provo, Utah, USA. He enjoys
            programming the Nintendo DS and Game Boy Advance, FPGA
            coding, and unicycling in his free time.
        </p></div></div></body></html>
